/*
 * 
 * Created on May 25, 2005
 * 
 * György Süveges
 * Etixpert Kft.
 * Copyright(c) 2005
 * 
 */
package com.etixpert.evolution;

import java.util.*;
import java.sql.*;


/**
 * @author Suveges Gyorgy
 *
 * TODO To change the template for this generated type comment go to
 * Window - Preferences - Java - Code Style - Code Templates
 */
public class Distributor extends PersistableObject {

    /**
     * @param table
     * @param PK
     */
    public Distributor() {
        
        super("distributor", new ArrayList());
        primaryKeys.add("id");
        
        
        // TODO Auto-generated constructor stub
    }

    /**
     * @param table
     * @param PK
     * @param values
     */
    public Distributor(Map values) {
        this();
        this.values = values;
        // TODO Auto-generated constructor stub
    }
    
    public Distributor(int value) {
        this();
        values = new HashMap();
        values.put("id", new Integer(value));
        
    }
   
    public void insert(Connection conn) throws EvolutionException, SQLException {
        if (!values.containsKey("id"))
            generateID();
        
        super.insert(conn);
    }
    public void insert() throws EvolutionException, SQLException {
        if (!values.containsKey("id"))
            generateID();
        
        super.insert();
        
    }
    
    /**
     * generates id for the new distributor and stores it in the values map
     * 
     * @return the generated ID
     * @throws EvolutionException
     * @throws SQLException
     */
    public int generateID() throws EvolutionException, SQLException {
        if (get("country_code")==null)
            throw new EvolutionException("country_code mut be given to generate the id");
        
        Connection conn = HibernateUtil.currentSession().connection();
        
        
        String sql = "{call generate_next_dist_id('"+get("country_code")+"')}";
        logger.info("Generating id: "+sql);
        CallableStatement stat = conn.prepareCall(sql);
        stat.execute();
        ResultSet rs = stat.getResultSet();
        rs.next();
        int id = rs.getInt(1);
        rs.close();
        
        stat.close();
        
        HibernateUtil.closeSession();
        values.put("id", new Integer(id));
        
        return id;
       
    }

}
