/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package moduloSeguridad.servlets;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.ws.WebServiceRef;
import moduloSeguridad.services.UsuarioService;
import org.apache.commons.codec.digest.DigestUtils;
import org.json.JSONArray;
import org.json.JSONObject;
import pe.siso.planillaws.service.Personal;
import pe.siso.planillaws.service.PersonalService_Service;
import pe.siso.planillaws.service.TipoDocumento;
import pe.siso.planillaws.service.TipoDocumentoService_Service;

/**
 *
 * @author Felipe Escala
 */
public class UsuarioServlet extends HttpServlet {

	@WebServiceRef(wsdlLocation = "WEB-INF/wsdl/app9.sacooliveros.edu.pe_8080/PlanillaWS/PersonalService.wsdl")
	private PersonalService_Service service_1;

	@WebServiceRef(wsdlLocation = "WEB-INF/wsdl/app9.sacooliveros.edu.pe_8080/PlanillaWS/TipoDocumentoService.wsdl")
	private TipoDocumentoService_Service service;

	@Override
	protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		response.setContentType("text/html");
		String accion = request.getParameter("accion");
		switch (accion) {
			case "listarUsuario":
				listarUsuario(request, response);
				break;
			case "editarUsuario":
				editarUsuario(request, response);
				break;
			case "activarUsuario":
				activarUsuario(request, response);
				break;
			case "desactivarUsuario":
				desactivarUsuario(request, response);
				break;
			case "listarTipoDocumento":
				listarTipoDoc(request, response);
				break;
			case "crearUsuario":
				crearUsuario(request, response);
				break;
			case "listarDatos":
				listarDatos(request, response);
				break;
			case "validarUsuario":
				validarUsuario(request, response);
				break;
			case "eliminarUsuario":
				eliminarUsuario(request, response);
				break;
			case "listarUsuarioDetalle":
				listarUsuarioDetalle(request, response);
				break;
			case "eliminarUsuarioDetalle":
				eliminarUsuarioDetalle(request, response);
				break;
			case "activarUsuarioDetalle":
				activarUsuarioDetalle(request, response);
				break;
			case "desactivarUsuarioDetalle":
				desactivarUsuarioDetalle(request, response);
				break;
			case "listarProyectos":
				listarProyectos(request, response);
				break;
			case "listarTipoDeUsuario":
				listarTipoDeUsuario(request, response);
				break;
			case "asignarProyectoUsuario":
				asignarProyectoUsuario(request, response);
				break;
			case "validarUsuarioDependencia":
				validarUsuarioDependencia(request, response);
				break;
			case "validarNombreUsuario":
				validarNombreUsuario(request, response);
				break;
			case "validarAsignacion":
				validarAsignacion(request, response);
				break;
			case "listarUsuarioManual":
				listarUsuarioManual(request, response);
				break;
			case "listarCargosDeUsuario":
				listarCargosDeUsuario(request, response);
				break;
			default:
				break;
		}
	}

	private void listarUsuario(HttpServletRequest request, HttpServletResponse response) throws IOException {
		response.setContentType("application/json");
		PrintWriter out = response.getWriter();
		UsuarioService srv = new UsuarioService();
		JSONArray lista = new JSONArray();
		JSONObject retorno = new JSONObject();
		String jsonString = request.getParameter("json");
		JSONObject filtro = new JSONObject(jsonString);
		String draw = request.getParameter("draw");
		int vstart = Integer.parseInt(request.getParameter("start"));
		int vlength = Integer.parseInt(request.getParameter("length"));
		JSONArray json = srv.listarUsuario(filtro, vstart, vlength, Integer.parseInt(draw));
		for (int i = 0; i < json.length(); i++) {
			JSONObject objeto = new JSONObject();
			JSONObject obj = json.getJSONObject(i);
			String codigoTrabajador = obj.getString("codigoTrabajador");
			JSONObject prs = new JSONObject(listarPersonalPorCodigo(codigoTrabajador));

			objeto.put("codigoUsuario", obj.getInt("codigoUsuario"));
			objeto.put("numeral", obj.getInt("numeral"));
			objeto.put("usuario", obj.getString("usuario"));
			objeto.put("estadoUsuario", obj.getInt("estadoUsuario"));
			objeto.put("nombreArea", prs.getString("nomAre"));
			objeto.put("nombreCargo", prs.getString("nomCar"));
			objeto.put("nombreUsuario", prs.getString("nomPer") + " " + prs.getString("apePatPer") + " " + prs.getString("apeMatPer"));
			objeto.put("nombreSede", prs.getString("nomSed"));

			lista.put(objeto);
		}
		int cantidad = srv.cantidadRegistros(filtro);
		retorno.put("data", lista);
		retorno.put("draw", draw);
		retorno.put("recordsFiltered", cantidad);
		retorno.put("recordsTotal", cantidad);
		out.print(retorno);
	}

	private void editarUsuario(HttpServletRequest request, HttpServletResponse response) throws IOException {
		response.setContentType("application/json");
		PrintWriter out = response.getWriter();
		UsuarioService srv = new UsuarioService();
		String usuario = request.getParameter("usuario");
		String clave = request.getParameter("clave");
		int codigo = Integer.parseInt(request.getParameter("codigo"));
		String passwordEncriptado = DigestUtils.md5Hex(clave);
		int rs = srv.editarUsuario(codigo, usuario, passwordEncriptado);
		out.println(rs);
	}

	private void activarUsuario(HttpServletRequest request, HttpServletResponse response) throws IOException {
		response.setContentType("application/json");
		PrintWriter out = response.getWriter();
		UsuarioService srv = new UsuarioService();
		int codigo = Integer.parseInt(request.getParameter("codigo"));
		int rs = srv.activarUsuario(codigo);
		out.println(rs);
	}

	private void desactivarUsuario(HttpServletRequest request, HttpServletResponse response) throws IOException {
		response.setContentType("application/json");
		PrintWriter out = response.getWriter();
		UsuarioService srv = new UsuarioService();
		int codigo = Integer.parseInt(request.getParameter("codigo"));
		int rs = srv.desactivarUsuario(codigo);
		out.println(rs);
	}

	private void crearUsuario(HttpServletRequest request, HttpServletResponse response) throws IOException {
		response.setContentType("application/json");
		PrintWriter out = response.getWriter();
		UsuarioService srv = new UsuarioService();
		String codigoTrabajador = request.getParameter("codTrabajador");
		String usuario = request.getParameter("usuario");
		String clave = request.getParameter("clave");
		String passwordEncriptado = DigestUtils.md5Hex(clave);
		int rs = srv.crearUsuario(codigoTrabajador, usuario, passwordEncriptado);
		out.println(rs);
	}

	private void listarTipoDoc(HttpServletRequest request, HttpServletResponse response) throws IOException {
		response.setContentType("application/json");
		PrintWriter out = response.getWriter();
		JSONArray array = new JSONArray();
		List<TipoDocumento> lista = listarTipoDocumento();
		for (int i = 0; i < lista.size(); i++) {
			JSONObject rs = new JSONObject();
			rs.put("codTipoDocumento", lista.get(i).getCodTipoDocumento());
			rs.put("tipoDocumento", lista.get(i).getNomCor());
			rs.put("longitud", lista.get(i).getLon());
			array.put(rs);
		}

		out.println(array);
	}

	private void listarDatos(HttpServletRequest request, HttpServletResponse response) throws IOException {
		response.setContentType("application/json");
		PrintWriter out = response.getWriter();
		String tipoDocumento = request.getParameter("tipoDocumento");
		String numeroDocumento = request.getParameter("numeroDocumento");
		JSONObject rs = new JSONObject(listarPersonalPorTipoDocNumDoc(tipoDocumento, numeroDocumento, "1"));
		out.println(rs);
	}

	private void validarUsuario(HttpServletRequest request, HttpServletResponse response) throws IOException {
		response.setContentType("application/json");
		PrintWriter out = response.getWriter();
		UsuarioService srv = new UsuarioService();
		String codigo = request.getParameter("codigo");
		int rs = srv.validarUsuario(codigo);
		out.println(rs);
	}

	private void eliminarUsuario(HttpServletRequest request, HttpServletResponse response) throws IOException {
		response.setContentType("application/json");
		PrintWriter out = response.getWriter();
		UsuarioService srv = new UsuarioService();
		int codigo = Integer.parseInt(request.getParameter("codigo"));
		int rs = srv.eliminarUsuario(codigo);
		out.println(rs);
	}

	private void listarUsuarioDetalle(HttpServletRequest request, HttpServletResponse response) throws IOException {
		response.setContentType("application/json");
		PrintWriter out = response.getWriter();
		UsuarioService srv = new UsuarioService();
		String filtro = request.getParameter("filtro");
		String draw = request.getParameter("draw");
		int vstart = Integer.parseInt(request.getParameter("start"));
		int vlength = Integer.parseInt(request.getParameter("length"));
		JSONObject json = srv.listarUsuarioDetalle(filtro, vstart, vlength, draw);
		out.println(json);
	}

	private void eliminarUsuarioDetalle(HttpServletRequest request, HttpServletResponse response) throws IOException {
		response.setContentType("application/json");
		PrintWriter out = response.getWriter();
		UsuarioService srv = new UsuarioService();
		int codigo = Integer.parseInt(request.getParameter("codigo"));
		int rs = srv.eliminarUsuarioDetalle(codigo);
		out.println(rs);
	}

	private void activarUsuarioDetalle(HttpServletRequest request, HttpServletResponse response) throws IOException {
		response.setContentType("application/json");
		PrintWriter out = response.getWriter();
		UsuarioService srv = new UsuarioService();
		int rs = 0;
		boolean array = Boolean.parseBoolean(request.getParameter("array"));
		if (array) {
			JSONArray lista = new JSONArray(request.getParameter("lista"));
			for (int i = 0; i < lista.length(); i++) {
				int codigo = lista.getInt(i);
				rs += srv.activarUsuarioDetalle(codigo);
			}
		} else {
			int codigo = Integer.parseInt(request.getParameter("codigo"));
			rs = srv.activarUsuarioDetalle(codigo);
		}
		out.println(rs);
	}

	private void desactivarUsuarioDetalle(HttpServletRequest request, HttpServletResponse response) throws IOException {
		response.setContentType("application/json");
		PrintWriter out = response.getWriter();
		UsuarioService srv = new UsuarioService();
		int codigo = Integer.parseInt(request.getParameter("codigo"));
		int rs = srv.desactivarUsuarioDetalle(codigo);
		out.println(rs);
	}

	private void listarProyectos(HttpServletRequest request, HttpServletResponse response) throws IOException {
		response.setContentType("application/json");
		PrintWriter out = response.getWriter();
		UsuarioService srv = new UsuarioService();
		JSONArray rs = srv.listarProyecto();
		out.println(rs);
	}

	private void listarTipoDeUsuario(HttpServletRequest request, HttpServletResponse response) throws IOException {
		response.setContentType("application/json");
		PrintWriter out = response.getWriter();
		UsuarioService srv = new UsuarioService();
		int codigo = Integer.parseInt(request.getParameter("codigo"));
		int usuario = Integer.parseInt(request.getParameter("usuario"));
		JSONArray rs = srv.listarTipoDeUsuario(codigo, usuario);
		out.println(rs);
	}

	private void asignarProyectoUsuario(HttpServletRequest request, HttpServletResponse response) throws IOException {
		response.setContentType("application/json");
		PrintWriter out = response.getWriter();
		UsuarioService srv = new UsuarioService();
		int usuario = Integer.parseInt(request.getParameter("usuario"));
		int proyectoDetalle = Integer.parseInt(request.getParameter("proyectoDetalle"));
		int rs = srv.asignarProyectoUsuario(usuario, proyectoDetalle);
		out.println(rs);
	}

	private void validarUsuarioDependencia(HttpServletRequest request, HttpServletResponse response) throws IOException {
		response.setContentType("application/json");
		PrintWriter out = response.getWriter();
		UsuarioService srv = new UsuarioService();
		int codigo = Integer.parseInt(request.getParameter("codigo"));
		int rs = srv.validarUsuarioDependencia(codigo);
		out.println(rs);
	}

	private void validarNombreUsuario(HttpServletRequest request, HttpServletResponse response) throws IOException {
		response.setContentType("application/json");
		PrintWriter out = response.getWriter();
		UsuarioService srv = new UsuarioService();
		String nombre = request.getParameter("nombre");
		int rs = srv.validarNombreUsuario(nombre);
		out.println(rs);
	}

	private void validarAsignacion(HttpServletRequest request, HttpServletResponse response) throws IOException {
		response.setContentType("application/json");
		PrintWriter out = response.getWriter();
		UsuarioService srv = new UsuarioService();
		int codigo = Integer.parseInt(request.getParameter("codigo"));
		int rs = srv.validarAsignacion(codigo);
		out.println(rs);
	}

	private java.util.List<pe.siso.planillaws.service.TipoDocumento> listarTipoDocumento() {
		// Note that the injected javax.xml.ws.Service reference as well as port objects are not thread safe.
		// If the calling of port operations may lead to race condition some synchronization is required.
		pe.siso.planillaws.service.TipoDocumentoService port = service.getTipoDocumentoServicePort();
		return port.listarTipoDocumento();
	}

	private Personal listarPersonalPorTipoDocNumDoc(java.lang.String tipoDocumento, java.lang.String numeroDocumento, java.lang.String estado) {
		// Note that the injected javax.xml.ws.Service reference as well as port objects are not thread safe.
		// If the calling of port operations may lead to race condition some synchronization is required.
		pe.siso.planillaws.service.PersonalService port = service_1.getPersonalServicePort();
		return port.listarPersonalPorTipoDocNumDoc(tipoDocumento, numeroDocumento, estado);
	}

	private Personal listarPersonalPorCodigo(java.lang.String tipoDocumento) {
		// Note that the injected javax.xml.ws.Service reference as well as port objects are not thread safe.
		// If the calling of port operations may lead to race condition some synchronization is required.
		pe.siso.planillaws.service.PersonalService port = service_1.getPersonalServicePort();
		return port.listarPersonalPorCodigo(tipoDocumento);
	}

	private void listarUsuarioManual(HttpServletRequest request, HttpServletResponse response) throws IOException {
		response.setContentType("application/json");
		PrintWriter out = response.getWriter();
		String jsonString = request.getParameter("json");
		JSONObject jsonObject = new JSONObject(jsonString);
		String busqueda = jsonObject.getString("busqueda");
		int tipo = jsonObject.getInt("tipo");
		UsuarioService srv = new UsuarioService();
		JSONObject json = srv.listarUsuarioManual(jsonObject);
		JSONArray listaFinal = new JSONArray();
		JSONArray lista = json.getJSONArray("results");
		for (int i = 0; i < lista.length(); i++) {
			JSONObject _final = new JSONObject();
			JSONObject obj = lista.getJSONObject(i);
			String codigoTrabajador = obj.getString("codigoTrabajador");
			JSONObject prs = new JSONObject(listarPersonalPorCodigo(codigoTrabajador));
			String nombreCompleto = prs.getString("nomPer") + " " + prs.getString("apePatPer") + " " + prs.getString("apeMatPer");
			String cargo = prs.getString("nomCar");
			if (tipo == 4 && (nombreCompleto.toUpperCase()).contains(busqueda.toUpperCase())) {
				_final.put("codigoUsuario", obj.getInt("codigoUsuario"));
				_final.put("numeral", obj.getInt("numeral"));
				_final.put("usuario", obj.getString("usuario"));
				_final.put("estadoUsuario", obj.getInt("estadoUsuario"));
				_final.put("nombreArea", prs.getString("nomAre"));
				_final.put("nombreCargo", prs.getString("nomCar"));
				_final.put("nombreUsuario", prs.getString("nomPer") + " " + prs.getString("apePatPer") + " " + prs.getString("apeMatPer"));
				_final.put("nombreSede", prs.getString("nomSed"));
				listaFinal.put(_final);
			} else if (tipo == 5 && (cargo.toUpperCase()).equals(busqueda.toUpperCase())) {
				_final.put("codigoUsuario", obj.getInt("codigoUsuario"));
				_final.put("numeral", obj.getInt("numeral"));
				_final.put("usuario", obj.getString("usuario"));
				_final.put("estadoUsuario", obj.getInt("estadoUsuario"));
				_final.put("nombreArea", prs.getString("nomAre"));
				_final.put("nombreCargo", prs.getString("nomCar"));
				_final.put("nombreUsuario", prs.getString("nomPer") + " " + prs.getString("apePatPer") + " " + prs.getString("apeMatPer"));
				_final.put("nombreSede", prs.getString("nomSed"));
				listaFinal.put(_final);
			}
		}
		out.println(listaFinal);
	}

	private void listarCargosDeUsuario(HttpServletRequest request, HttpServletResponse response) throws IOException {
		response.setContentType("application/json");
		PrintWriter out = response.getWriter();
		UsuarioService srv = new UsuarioService();
		JSONObject json = srv.listarUsuarioManual(new JSONObject());
		ArrayList<String> cargos = new ArrayList<>();
		JSONArray lista = json.getJSONArray("results");
		for (int i = 0; i < lista.length(); i++) {
			JSONObject obj = lista.getJSONObject(i);
			JSONObject prs = new JSONObject(listarPersonalPorCodigo(obj.getString("codigoTrabajador")));
			if (!cargos.contains(prs.getString("nomCar"))) {
				cargos.add(prs.getString("nomCar"));
			}
		}
		out.print(new JSONArray(cargos));
	}
}
