package com.etixpert.evolution;

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


public class Interessent extends PersistableObject {

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

    /**
     * @param table
     * @param PK
     * @param values
     */
    public Interessent(Map values) {
        this();
        this.values = values;
        // TODO Auto-generated constructor stub
    }
    
    public Interessent(int value) {
        this();
        values = new HashMap();
        values.put("id", new Integer(value));
        
    }
   
    public void insert(Connection conn) throws EvolutionException, SQLException {
        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 must be given to generate the id");
        
        Connection conn = HibernateUtil.currentSession().connection();
        
        
        String sql = "{call generate_next_int_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;
       
    }

}
