package br.com.centralit.citcorpore.ajaxForms;

import java.io.File;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import br.com.centralit.citajax.html.AjaxFormAction;
import br.com.centralit.citajax.html.DocumentHTML;
import br.com.centralit.citajax.html.HTMLSelect;
import br.com.centralit.citcorpore.bean.CargaWebServiceDTO;
import br.com.centralit.citcorpore.bean.ScriptsDTO;
import br.com.centralit.citcorpore.negocio.ScriptsService;
import br.com.centralit.citcorpore.util.CITCorporeUtil;
import br.com.centralit.citcorpore.util.Enumerados;
import br.com.centralit.citcorpore.util.WebUtil;
import br.com.centralit.citsmart.rest.service.RestOperationService;
import br.com.citframework.dto.Usuario;
import br.com.citframework.service.ServiceLocator;
import br.com.citframework.util.SQLConfig;
import br.com.citframework.util.UtilI18N;

public class CargaWebService extends AjaxFormAction {
	
	private String caminhoArquivo = CITCorporeUtil.CAMINHO_REAL_APP + "sqls" + System.getProperty("file.separator") + "webservice";
	
	@Override
    public void load(DocumentHTML document, HttpServletRequest request, HttpServletResponse response) throws Exception {
    	this.carregaCombo(document, request, response);
    }
	
    private void carregaCombo(DocumentHTML document, HttpServletRequest request, HttpServletResponse response){
    	try{
	    	final HTMLSelect combo = document.getSelectById("idioma");
	    	combo.addOption("", UtilI18N.internacionaliza(request, "curriculo.idioma"));
    		combo.addOption("pt", UtilI18N.internacionaliza(request, "idioma.portugues"));
    		combo.addOption("en", UtilI18N.internacionaliza(request, "idioma.ingles"));
    		combo.addOption("es", UtilI18N.internacionaliza(request, "idioma.espanhol"));
    	}catch(Exception e){
    		document.alert(e.getMessage());
    	}
    }
    
	public void executarCarga(DocumentHTML document, HttpServletRequest request, HttpServletResponse response) {
		try{
			CargaWebServiceDTO carga = (CargaWebServiceDTO) document.getBean();
			
			if(!WebUtil.validarSeUsuarioEstaNaSessao(request, document)){
				return;
			}
			
			final Usuario usuario = WebUtil.getUsuarioSistema(request);
			
			if(carga.getIdioma().isEmpty()){
				document.alert(UtilI18N.internacionaliza(request, "situacaoLiberacaoMudanca.selecione"));
				document.executeScript("JANELA_AGUARDE_MENU.hide();");
				return;
			}
			
			RestOperationService restOperationService = (RestOperationService) ServiceLocator.getInstance().getService(RestOperationService.class, usuario);

			if(restOperationService.existeRegistroCadastrado()){
				document.executeScript("sobrecarregar();");
				return;
			}
			
			String script = doScript(carga.getIdioma(), Enumerados.SimNao.NAO.getValorUmDois());
			ScriptsDTO s= new ScriptsDTO();
			s.setNome("Carga Web Service");
			s.setDescricao("Script carregado na tela de carga Web Service no idioma selecionado "+carga.getIdioma());
			s.setSqlQuery(script);
			ScriptsService scriptsService = (ScriptsService) ServiceLocator.getInstance().getService(ScriptsService.class, usuario);
			scriptsService.executarScriptUpdateCompletamente(s);
			
			document.executeScript("JANELA_AGUARDE_MENU.hide();");
			document.alert(UtilI18N.internacionaliza(request, "cargaPaises.msg.Sucesso"));
		}catch(Exception e){
			document.executeScript("JANELA_AGUARDE_MENU.hide();");
			document.alert(UtilI18N.internacionaliza(request, "MSE02"));
		}
	}
	
	public void sobrecarregarCargaDeDados(DocumentHTML document, HttpServletRequest request, HttpServletResponse response) {
		try{
			CargaWebServiceDTO carga = (CargaWebServiceDTO) document.getBean();
			
			if(!WebUtil.validarSeUsuarioEstaNaSessao(request, document)){
				return;
			}
			
			final Usuario usuario = WebUtil.getUsuarioSistema(request);
			
			if(carga.getIdioma().isEmpty()){
				document.alert(UtilI18N.internacionaliza(request, "situacaoLiberacaoMudanca.selecione"));
				document.executeScript("JANELA_AGUARDE_MENU.hide();");
				return;
			}
			
			String script = doScript(carga.getIdioma(), Enumerados.SimNao.SIM.getValorUmDois());
			ScriptsDTO s= new ScriptsDTO();
			s = new ScriptsDTO();
			s.setNome("Carga Web Service");
			s.setDescricao("Script carregado na tela de carga Web Service no idioma selecionado "+carga.getIdioma());
			s.setSqlQuery(script);
			ScriptsService scriptsService = (ScriptsService) ServiceLocator.getInstance().getService(ScriptsService.class, usuario);
			scriptsService.executarScriptUpdateCompletamente(s);
			
			document.executeScript("JANELA_AGUARDE_MENU.hide();");
			document.alert(UtilI18N.internacionaliza(request, "cargaPaises.msg.Sucesso"));
			
		}catch(Exception e){
			document.executeScript("JANELA_AGUARDE_MENU.hide();");
			document.alert(UtilI18N.internacionaliza(request, "MSE02"));
		}
	}
	
	/**
	 * Constroi o caminho do arquivo de script 
	 * @param idioma 
	 * @param atualiza
	 * @return
	 * @throws Exception
	 */
    private String doScript(String idioma, Integer atualiza) throws Exception{
    	
    	File f;
    	switch(idioma){
    		case "delete":
    			f = new File(caminhoArquivo+System.getProperty("file.separator")+"delete_cargawebservice.sql");
	    		break;
    		case "es":
    			if(CITCorporeUtil.SGBD_PRINCIPAL.toUpperCase().equals(SQLConfig.MYSQL)){
    				f = new File(caminhoArquivo.concat(System.getProperty("file.separator")).concat("MySQL").concat(System.getProperty("file.separator")).concat("webservice_es_mysql.sql"));
    				
				}else if(CITCorporeUtil.SGBD_PRINCIPAL.toUpperCase().equals(SQLConfig.ORACLE)){
    				f = new File(caminhoArquivo.concat(System.getProperty("file.separator")).concat("Oracle").concat(System.getProperty("file.separator")).concat("webservice_es_oracle.sql"));
    				
				}else if(CITCorporeUtil.SGBD_PRINCIPAL.toUpperCase().equals(SQLConfig.POSTGRESQL)){
    				f = new File(caminhoArquivo.concat(System.getProperty("file.separator")).concat("PostgreSQL").concat(System.getProperty("file.separator")).concat("webservice_es_postgres.sql"));
    				
				}else if(CITCorporeUtil.SGBD_PRINCIPAL.toUpperCase().equals(SQLConfig.SQLSERVER)){
    				f = new File(caminhoArquivo.concat(System.getProperty("file.separator")).concat("SqlServer").concat(System.getProperty("file.separator")).concat("webservice_es_sqlserver.sql"));

				}else{
					f = null;
				}
    			
	    		break;
    		case "en":
    			if(CITCorporeUtil.SGBD_PRINCIPAL.toUpperCase().equals(SQLConfig.MYSQL)){
    				f = new File(caminhoArquivo.concat(System.getProperty("file.separator")).concat("MySQL").concat(System.getProperty("file.separator")).concat("webservice_en_mysql.sql"));
    				
				}else if(CITCorporeUtil.SGBD_PRINCIPAL.toUpperCase().equals(SQLConfig.ORACLE)){
    				f = new File(caminhoArquivo.concat(System.getProperty("file.separator")).concat("Oracle").concat(System.getProperty("file.separator")).concat("webservice_en_oracle.sql"));
    				
				}else if(CITCorporeUtil.SGBD_PRINCIPAL.toUpperCase().equals(SQLConfig.POSTGRESQL)){
    				f = new File(caminhoArquivo.concat(System.getProperty("file.separator")).concat("PostgreSQL").concat(System.getProperty("file.separator")).concat("webservice_en_postgres.sql"));
    				
				}else if(CITCorporeUtil.SGBD_PRINCIPAL.toUpperCase().equals(SQLConfig.SQLSERVER)){
    				f = new File(caminhoArquivo.concat(System.getProperty("file.separator")).concat("SqlServer").concat(System.getProperty("file.separator")).concat("webservice_en_sqlserver.sql"));

				}else{
					f = null;
				}

   		 		break;
   		 	default:
	   		 	if(CITCorporeUtil.SGBD_PRINCIPAL.toUpperCase().equals(SQLConfig.MYSQL)){
	   		 		f = new File(caminhoArquivo.concat(System.getProperty("file.separator")).concat("MySQL").concat(System.getProperty("file.separator")).concat("webservice_pt_mysql.sql"));
					
				}else if(CITCorporeUtil.SGBD_PRINCIPAL.toUpperCase().equals(SQLConfig.ORACLE)){
					f = new File(caminhoArquivo.concat(System.getProperty("file.separator")).concat("Oracle").concat(System.getProperty("file.separator")).concat("webservice_pt_oracle.sql"));
					
				}else if(CITCorporeUtil.SGBD_PRINCIPAL.toUpperCase().equals(SQLConfig.POSTGRESQL)){
					f = new File(caminhoArquivo.concat(System.getProperty("file.separator")).concat("PostgreSQL").concat(System.getProperty("file.separator")).concat("webservice_pt_postgres.sql"));
					
				}else if(CITCorporeUtil.SGBD_PRINCIPAL.toUpperCase().equals(SQLConfig.SQLSERVER)){
					f = new File(caminhoArquivo.concat(System.getProperty("file.separator")).concat("SqlServer").concat(System.getProperty("file.separator")).concat("webservice_pt_sqlserver.sql"));
				
				}else{
					f = null;
				}
   		 		
   		 		break;
    	}
    	
    	String aux = "";
    	
    	if(f != null){
    		aux = new String(Files.readAllBytes(f.toPath()), StandardCharsets.ISO_8859_1);
    	}
    	
    	return aux;
    }

    @Override
    public Class<CargaWebServiceDTO> getBeanClass() {
        return CargaWebServiceDTO.class;
    }

}