package ve.gob.cnti.receiver.jdbc;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.logging.Logger;


import org.apache.commons.dbcp2.BasicDataSource;

import ve.gob.cnti.gestion.alfresco.AlfrescoLoadFiles;
import ve.gob.cnti.gestion.alfresco.FileMessage;
import ve.gob.cnti.receiver.utils.ConverDate;
import ve.gob.cnti.receiver.utils.IConvertDate;
import ve.gob.cnti.receiver.utils.PropertiesReader;


/**
 * Esta clase se encarga de extraer informacion de la tabla arch_process_instance_lastupdate, process_instance y data_instance
 * para implementar esta clase utilice la clase CaseImpl.java
 * @author Yamil Orozco
 */

public class ConnectionJDBC implements IConnectionJDBC {
	
	Connection cnn=null;
	Statement ps = null;
    ResultSet rs=null;
    private static BasicDataSource basicDataSource=null;
    PropertiesReader properties = new PropertiesReader();		
    public String DATABASE_URL = properties.getProperty("DATABASE_URL");
    public String DATABASE_USER = properties.getProperty("DATABASE_USER");
    public String DATABASE_PASSWORD = properties.getProperty("DATABASE_PASSWORD");
    public Integer MAX_CONNECTION = Integer.valueOf(properties.getProperty("MAX_CONNECTION"));
    public Integer INITIAL_CONNECTION = Integer.valueOf(properties.getProperty("INITIAL_CONNECTION"));
    public Integer MAX_IDLE = Integer.valueOf(properties.getProperty("MAX_IDLE"));
    public Integer MIN_IDLE = Integer.valueOf(properties.getProperty("MIN_IDLE"));
    public Boolean REMOVE_ABANDONED = Boolean.valueOf(properties.getProperty("REMOVE_ABANDONED"));
    public Integer REMOVE_ABANDONED_TIME = Integer.valueOf(properties.getProperty("REMOVE_ABANDONED_TIME"));
    private static final Logger log = Logger.getLogger(ConnectionJDBC.class.getName());
    Boolean next=null;
    
    public ConnectionJDBC(){
    	
    	basicDataSource=new BasicDataSource();
		basicDataSource.setDriverClassName("org.postgresql.Driver");
		basicDataSource.setUrl(DATABASE_URL);
		basicDataSource.setUsername(DATABASE_USER);
		basicDataSource.setPassword(DATABASE_PASSWORD);
		basicDataSource.setMaxTotal(MAX_CONNECTION);
		basicDataSource.setInitialSize(INITIAL_CONNECTION);
		basicDataSource.setValidationQuery("select 1");
		basicDataSource.setRemoveAbandonedOnBorrow(REMOVE_ABANDONED);
		basicDataSource.setRemoveAbandonedTimeout(REMOVE_ABANDONED_TIME);
		basicDataSource.setMaxIdle(MAX_IDLE);
		basicDataSource.setMinIdle(MIN_IDLE);	
		
    }
  
    
	public void openConnection(){		
		
		
		
	}
	
	
	public void insertRecordProcess(Map<String,String> variables){
			
			
			String query=null;
			log.info("instancia"+variables.get("id_instancia")+"cedula"+variables.get("cedula"));
			log.info("ingresando el registro del proceso finalizado");
			try {
				cnn =basicDataSource.getConnection();
				ps=cnn.createStatement();
				query="insert into proceso_instancias_hist (id_instancia, fecha_inicio,"
						+ "fecha_fin,cedula,nacionalidad,nombre,apellido,sexo,fecha_nac,pais_orig,estado_orig,"
						+ "municipio_orig,parroquia_orig,tramite,descripcion_proceso,datos_sol)"
						+ " values ("+Long.parseLong(variables.get("id_instancia"))+",'"
				+variables.get("f_solicitud")+"','"
				+variables.get("lastupdate")+"','"
				+variables.get("cedula")+"','"
				+variables.get("nacionalidad")+"','"
				+variables.get("nombre")+"','"
				+variables.get("apellido")+"','"
				+variables.get("sexo")+"','"
				+variables.get("f_nacimiento")+"','"
				+variables.get("pais")+"','"
				+variables.get("estado")+"','"
				+variables.get("municipio")+"','"
				+variables.get("parroquia")+"','"
				+variables.get("tramite")+"','"
				+variables.get("description")+"',"+null+") ";
			    log.info(query);
				ps.executeUpdate(query);
				

				try {
					if(ps!=null) ps.close();
					if(cnn!=null) cnn.close();
				} catch (SQLException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				}	
				
				
							
				Iterator<Entry<String,String>> iteratorMap=variables.entrySet().iterator();
				query="update proceso_instancias_hist set datos_sol=(SELECT xmlelement(name instancia,";
				cnn =basicDataSource.getConnection();
				ps=cnn.createStatement();
				while ( iteratorMap.hasNext() )
				  { 
					
					Entry<String,String> values  =  iteratorMap.next();
				    query+="xmlelement(name "+values.getKey()+",'"+values.getValue()+"')";
				    if(iteratorMap.hasNext()){
				    	query+=",";
				    }
				  }
				 query+=")) where id_instancia="+Long.parseLong(variables.get("id_instancia"));				 
				 ps.executeUpdate(query);	
					
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				
			}	  
			
			try {
				if(ps!=null) ps.close();
				if(cnn!=null) cnn.close();
			} catch (SQLException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}	
			
				
			
	}
	
	
	public void insertRecordCiudadanoArchivos(Map<String,String> variables){
		IConvertDate converter=new ConverDate();
		String query=null;		
		log.info("ingresando el registro de los archivos que consultara el funcionario");
		try {
			cnn =basicDataSource.getConnection();
			ps=cnn.createStatement();
			query="insert into ciudadano (hash, id_tramite,"
					+ "tipo_tramite,descripcion,task_id,task_name,task_description, email,nombre,"
					+ "f_solicitud,email_generico, cedula,bloquear,revision)"
					+ " values ('"
			+variables.get("hash")+"','"
			+variables.get("id_tramite")+"','"
			+variables.get("tipo_tramite")+"','"
			+variables.get("descripcion_tramite")+"','"
			+variables.get("taskId")+"','"
			+variables.get("taskName")+"','"
			+variables.get("taskDescription")+"','"
			+variables.get("email")+"','"
			+variables.get("nombre")+"','"
			+converter.getFormattedLongDateDate("yyyy-MM-dd",variables.get("f_solicitud"))+"','"
			+variables.get("emailNotificador")+"','"
			
			+variables.get("cedula")+"','no','"
			+variables.get("revision")+
			"')";
			log.info("query "+query);
			ps.executeUpdate(query);			
			
			try {
				if(ps!=null) ps.close();
				if(cnn!=null) cnn.close();
			} catch (SQLException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}			
			cnn =basicDataSource.getConnection();
			ps=cnn.createStatement();
			
			query="insert into email_funcionario_gi (hash, email)"
					+ " values ('"
			+variables.get("hash")+"','"
			+variables.get("emailSGI")+"')";
			log.info("query "+query);
			ps.executeUpdate(query);
			
			try {
				if(ps!=null) ps.close();
				if(cnn!=null) cnn.close();
			} catch (SQLException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
			
			Iterator<Entry<String,String>> variableIterator=variables.entrySet().iterator();
			
			
			cnn =basicDataSource.getConnection();
			ps=cnn.createStatement();
			
			while(variableIterator.hasNext()){
				
				Entry<String,String> values  =  variableIterator.next();
				AlfrescoLoadFiles alfresco=new AlfrescoLoadFiles();
				FileMessage document=null;
				String[] elementos=null;
				log.info("concide "+values.getValue().indexOf("_FILE")+" value"+values.getValue()+ " key "+values.getKey());
				if(values.getKey().indexOf("_FILE")>=0&&
				   values.getValue().indexOf("[")>=0&&
				   values.getValue().indexOf("]")>=0&&
				   values.getValue()!=null
				   &&!values.getValue().equals("[]")
				   &&!values.getValue().equals("[, ]")				   
				   ){
				   elementos=values.getValue().replace("[", "").replace("]", "").split(",");
				   for(int i=0;i<elementos.length;i++){
					   if(elementos[i]!=null&&!elementos[i].equals("")){
						   document=alfresco.getFileMessage(elementos[i].trim());				
						   query="insert into archivos (hash,codigo_archivo,nombre) values ('"+variables.get("hash")+"','"+elementos[i]+"','"+document.getName()+"') ";
						   ps.executeUpdate(query);
					   }
				   }
				}else if(values.getKey().indexOf("_FILE")>=0&&
						 values.getValue()!=null&&
						!values.getValue().equals("[]")
						&&!values.getValue().equals("[, ]")&&			
						!values.getValue().equals("")){
					 document=alfresco.getFileMessage(values.getValue().trim());	
				
					query="insert into archivos (hash,codigo_archivo,nombre) values ('"+variables.get("hash")+"','"+values.getValue()+"','"+document.getName()+"') ";
					ps.executeUpdate(query);
				}
				
			}
				
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			
		}	
		
		
		try {
			
			if(ps!=null) ps.close();
			if(cnn!=null) cnn.close();
		} catch (SQLException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		
			
		
}
	public Boolean verifyUser(String hash){
		Boolean acceso=false;
		try {
				cnn =basicDataSource.getConnection();
				ps=cnn.createStatement();		
				String query="select * from ciudadano where trim(hash)='"+hash.trim()+"'";
				rs=ps.executeQuery(query);		
				while(rs.next()){
					acceso=true;		
				}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		
		
		try {
			if(rs!=null)rs.close();
			if(ps!=null) ps.close();
			if(cnn!=null) cnn.close();
		} catch (SQLException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		
		
		
		return acceso;
	}
	
	public void deleteRecordDocuments(long instanceProcessId){
		try {
			cnn =basicDataSource.getConnection();
			ps=cnn.createStatement();
			String query="select * from ciudadano where id_tramite="+instanceProcessId;
			rs=ps.executeQuery(query);
			String hash=null;			
			while(rs.next()){
				hash=rs.getString("hash");
				break;
			}
			if(hash!=null){
				query="delete * from archivos where trim(hash) like '"+hash+"'";
				ps.executeUpdate(query);
				query="delete * from ciudadano where trim(hash) like '"+hash+"'";
				ps.executeUpdate(query);
			}
			
			
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		try {
			if(rs!=null)rs.close();
			if(ps!=null) ps.close();
			if(cnn!=null) cnn.close();
		} catch (SQLException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		
	}
	
	public void closeConnection(){
		
		try {
			/*ps.close();
			cnn.close();*/
			basicDataSource.close();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	

	
    
	

}
