package com.dacrt.SBIABackend.controler;

import java.text.Normalizer;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Optional;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import javax.persistence.TypedQuery;
import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import com.dacrt.SBIABackend.dto.FacilitResponseDto;
import com.dacrt.SBIABackend.dto.FacilitResponseDto2;
import com.dacrt.SBIABackend.dto.FacilitiesListDto;
import com.dacrt.SBIABackend.dto.FacilitiesResponseDto;
import com.dacrt.SBIABackend.dto.FacilitiesResponseDto2;
import com.dacrt.SBIABackend.dto.FacilitiesResponseDto3;
import com.dacrt.SBIABackend.dto.IddscDto;
import com.dacrt.SBIABackend.dto.StatusDto2;
import com.dacrt.SBIABackend.dto.TypesUnitDto;
import com.dacrt.SBIABackend.dto.VicepresResponseDto;
import com.dacrt.SBIABackend.dto.VicepresidenciesListDto;
import com.dacrt.SBIABackend.dto.VicepresidenciesResponseDto;
import com.dacrt.SBIABackend.dto.requestDto.FacilitiesRequestDto;
import com.dacrt.SBIABackend.dto.requestDto.WorkersRequestBodyDto;
import com.dacrt.SBIABackend.dto.responseDto.FacilitiesEntryDto;
import com.dacrt.SBIABackend.entity.Facilities;
import com.dacrt.SBIABackend.entity.Vicepresidencies;
import com.dacrt.SBIABackend.repository.FacilitiesRepository;
import com.dacrt.SBIABackend.security.dto.AuditRequestDto;
import com.dacrt.SBIABackend.security.dto.ParamsDto;
import com.dacrt.SBIABackend.security.dto.ParamsResponseDto;
import com.dacrt.SBIABackend.security.dto.PrivilegesAllDto;
import com.dacrt.SBIABackend.security.dto.PrivilegesDto;
import com.dacrt.SBIABackend.security.dto.RespuestaDto;
import com.dacrt.SBIABackend.security.dto.RespuestaMsgDto;
import com.dacrt.SBIABackend.security.dto.RespuestaValueDto;
import com.dacrt.SBIABackend.security.dto.RoleDto;
import com.dacrt.SBIABackend.security.entity.Params;
import com.dacrt.SBIABackend.security.entity.Roles;
import com.dacrt.SBIABackend.security.entity.Users;
import com.dacrt.SBIABackend.security.repository.AuditRepository;
import com.dacrt.SBIABackend.security.repository.ParamsRepository;
import com.dacrt.SBIABackend.security.repository.PrivilegesRepository;
import com.dacrt.SBIABackend.security.repository.RolesPrivilegesRepository;
import com.dacrt.SBIABackend.security.repository.UsersRepository;
import com.dacrt.SBIABackend.security.service.MenuService;
import com.dacrt.SBIABackend.security.service.ParamsService;
import com.dacrt.SBIABackend.security.service.SecurityService;
import com.dacrt.SBIABackend.security.service.UsersService;
import com.dacrt.SBIABackend.service.FacilitiesService;
import com.dacrt.SBIABackend.utils.HttpReqRespUtils;

@RestController
@CrossOrigin(origins = "*")
public class FacilitiesControler {
	@PersistenceContext
	private EntityManager entityManager;

	@Autowired
	private PrivilegesRepository privilegesRepository;

	@Autowired
	private ParamsRepository paramsRepository;

	@Autowired
	private AuditRepository auditRepository;

	@Autowired
	private UsersRepository usersRepository;
	
	@Autowired
	private FacilitiesRepository facilitiesRepository;
	
	@Autowired
	private RolesPrivilegesRepository rolesPrivilegesRepository;

	@Autowired
	MenuService menuService;

	@Autowired
	SecurityService securityService;
	
	@Autowired
	ParamsService paramsService;
	
	@Autowired
	FacilitiesService facilitiesService;

	@Autowired
	UsersService usersService;
	
	@Autowired
    private JdbcTemplate jdbcTemplate;
	
	@Value("${spring.datasource.url}")
	private String conexion;
	
	@Value("${spring.datasource.username}")
	private String userbd;
	
	@Value("${spring.datasource.password}")
	private String passbd;
	
	Logger logger = LoggerFactory.getLogger(FacilitiesControler.class);

	@PostMapping("/facilities")
	public ResponseEntity<?> listarFacilities(HttpServletRequest request,
			@RequestBody FacilitiesListDto tiposfiltros) throws ParseException {

		RespuestaMsgDto respuesta = new RespuestaMsgDto("");
		HttpStatus estatus = HttpStatus.FORBIDDEN;
		long cuantosregistro = 0;

		String sessionid = request.getHeader("Authorization");
		Date fecha = new Date();
		SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		String dataFormattata = formatter.format(fecha);

		String searchIn = "";
		int statusIn = 0;
		String searchModule = "";
		String searchUsr = "";
		String contentIn = "";
		int orderIn = 0;
		int offsetIn = 0;
		int numofrecordsIn = 0;
		int formatList=0;
		 int typeIn=0;
		 int idrol;
		 IddscDto detalletype = new IddscDto();
		 IddscDto detalleCertifi = new IddscDto();
		 IddscDto detalleGenerator = new IddscDto();
		 IddscDto detalleGas = new IddscDto();
		 IddscDto detalleUps = new IddscDto();
		 IddscDto detalleOwner = new IddscDto();
			TypesUnitDto detalleTypes;
    	  	List<TypesUnitDto> listasTypes = new ArrayList<>();
		Optional<Params> deSessDuration = paramsRepository.findByParamname("SESSION_DURATION");
		String SessionDuration = deSessDuration.get().getValue();
		int duracionSession = Integer.parseInt(SessionDuration);
		Date fecha2 = new Date();
		Calendar calendar = Calendar.getInstance();
		calendar.setTime(fecha2); // tuFechaBase es un Date;
		// calendar.add(Calendar.MINUTE, minutosASumar); //minutosASumar es int.
		calendar.add(Calendar.MINUTE, duracionSession); // horasASumar es int.
		// lo que más quieras sumar
		Date ValidThrufechaSalida = calendar.getTime(); // Y ya tienes la fecha sumada.
		SimpleDateFormat salida = new SimpleDateFormat("yyyy-MM-dd HH:mm"); // 2024-12-23 23:00
		String fechaComoCadena = salida.format(ValidThrufechaSalida);
		System.out.println(fechaComoCadena);

		// Verifico la session
		if (sessionid == null) {
			respuesta.setMsg("Llamada al servicio malformado");
			estatus = HttpStatus.BAD_REQUEST;
			return new ResponseEntity(respuesta, estatus);
		} else {
			sessionid = sessionid.substring(7);
			// verifico si la sesión del usuario existe.
			Optional<Users> encontreSessionUsuario = usersRepository.getBySessionid(sessionid);
			if (encontreSessionUsuario.isPresent()) { // si la sesión del usuario existe
				Date FechaReg = encontreSessionUsuario.get().getValidthru();
				// Llamada a la funcion que validad el tiempo de Session, retorna la fecha
				// sumandole el tiempo de session activa, y vacio si no esta activa
				fechaComoCadena = securityService.consultarSessionActiva(FechaReg, fecha2,
						encontreSessionUsuario.get().getId());

				if (fechaComoCadena == "") {
					RespuestaMsgDto respuestaDto2;
					String var2 = "";
					boolean bloked2 = false;
					respuestaDto2 = new RespuestaMsgDto(var2);
					respuestaDto2.setMsg("Sesión expirada o inválida");
					return new ResponseEntity(respuestaDto2, HttpStatus.UNAUTHORIZED);
				}

				// Este proceso permite obtener un listado de los procesos. (Priv 120)
				//formatList = tiposfiltros.getFormat();
				int rolisvalid = 0;
				Roles roles = encontreSessionUsuario.get().getRolid();
				idrol = roles.getId();
				rolisvalid = auditRepository.getCantbyRolAndPrivi(encontreSessionUsuario.get().getRolid().getId(), 480);
				  formatList = tiposfiltros.getFormat();
				    
				    if (formatList==0) {
				    	formatList = 1;
				    } else {
				    	formatList = tiposfiltros.getFormat();
				    }
				if (formatList!=2) {
				    if (rolisvalid==0) {
					respuesta.setMsg("No tiene los Privilegios");
					estatus = HttpStatus.FORBIDDEN;
					return new ResponseEntity(respuesta, estatus);
				  }
				}   

				// Obtengo los datos del Body
				searchIn = tiposfiltros.getFilters().getSearch();// dato de busqueda por nombre
				//quitarAcentosJava
				statusIn = tiposfiltros.getFilters().getStatus();
				searchModule = tiposfiltros.getFilters().getModule();
				searchUsr = tiposfiltros.getFilters().getUser();
				orderIn = tiposfiltros.getOrder(); // Orden Ascedente o Descendente
				offsetIn = tiposfiltros.getOffset();// Primer registro a mostrar
				numofrecordsIn = tiposfiltros.getNumofrecords();// Número de registros a mostrar
				contentIn = tiposfiltros.getContent();
				//String typeIn2 = tiposfiltros.getFilters().getType();
				//typeIn  = Integer.parseInt(typeIn2);
				  
				  try {
					  String typeIn2 = tiposfiltros.getFilters().getType();
					  typeIn  = Integer.parseInt(typeIn2);
						  if (typeIn==0) {
							  typeIn = 0;
						  }
						  
					  }  catch (Exception e) { 
						  
						  typeIn = 0;
						  
					  }
				  
				
				    
				// Verifico los Shorcouts
				if (contentIn != null && contentIn != "") {
					menuService.iscontentdiffnull(contentIn, encontreSessionUsuario.get().getId());
				}

			} else { // Si la sesión que viene es inválida
				respuesta.setMsg("Sesión expirada o inválida");
				estatus = HttpStatus.BAD_REQUEST;
				return new ResponseEntity(respuesta, estatus);
			}

			// Aqui empieza la carga de la data de respuesta

			FacilitResponseDto facili = new FacilitResponseDto();
			FacilitResponseDto2 facili2 = new FacilitResponseDto2();
			FacilitiesResponseDto facilitiesResponseDto = new FacilitiesResponseDto();
			FacilitiesResponseDto2 facilitiesResponseDto2 = new FacilitiesResponseDto2();
			FacilitiesResponseDto3 facilitiesResponseDto3 = new FacilitiesResponseDto3();
			PrivilegesAllDto detallePrivilege = new PrivilegesAllDto();
			List<FacilitiesResponseDto> facilitiesResultado = new ArrayList();

			List<FacilitiesResponseDto2> facilitiesResultado2 = new ArrayList();
			Query query = null;
			try {
				// Sentencia General
				String SentenciaBase="";
				if (formatList==2) {
					//SentenciaBase = "SELECT new com.dacrt.SBIABackend.dto.FacilitiesResponseDto(u.id,u.name,u.status) FROM Facilities u";
					SentenciaBase = "SELECT new com.dacrt.SBIABackend.dto.FacilitiesResponseDto3(u.id,u.name,u.status AS idStatus,CASE WHEN u.status = 1 THEN 'Activo' ELSE 'Inactivo' END AS decstatus) FROM Facilities u";
				}else {
					//SentenciaBase = "SELECT new com.dacrt.SBIABackend.dto.FacilitiesResponseDto3(v.id,v.name,v.status AS idStatus,CASE WHEN v.status = 1 THEN 'Activo' ELSE 'Inactivo' END AS decstatus) FROM Facilities v";
					
					SentenciaBase = " SELECT u.id,u.name,u.status,CASE WHEN u.status = 1 THEN 'Activo' ELSE 'Inactivo' END AS estatus,u.address, "
							+ " CAST(u.facilitytypepar AS TEXT) AS facilitytypepar,pr.descr AS desctype,CAST(u.certtypepar AS TEXT) AS certtypepar,pr1.descr AS desccerty,"
							+ " SUBSTRING(CAST(u.date AS TEXT),1,10) AS dated,SUBSTRING(CAST(u.expiration AS TEXT),1,10) AS expiration,u.country,u.region,"
							+ " CAST(u.generator AS TEXT) AS generator,pr2.descr as descgene,"
							+ " CAST(u.gasbackup AS TEXT) AS gasbackup,pr3.descr as descgas,"
							+ " CAST(u.ups AS TEXT) AS ups,pr4.descr as descups,"
							+ " CAST(u.ownership AS TEXT) AS ownership,pr5.descr as descowner"
							+ "					        FROM  main.Facilities u  "
							+ "					       LEFT JOIN ( SELECT elemento ->> 'dsc' AS descr,elemento ->> 'value' AS valor  "
							+ "					         FROM main.params p,  "
							+ "					             jsonb_array_elements(CAST(p.value AS jsonb)) AS elemento  "
							+ "					         WHERE p.paramname = 'FACILITY_TYPE') pr ON u.facilitytypepar = CAST(pr.valor AS INTEGER)  "
							+ "					         LEFT JOIN ( SELECT elemento ->> 'dsc' AS descr,elemento ->> 'value' AS valor  "
							+ "					         FROM main.params p,  "
							+ "					                jsonb_array_elements(CAST(p.value AS jsonb)) AS elemento   "
							+ "					            WHERE p.paramname = 'CERTIFICATION_TYPE') pr1 ON u.certtypepar = CAST(pr1.valor AS INTEGER)  "
							+ "                            LEFT JOIN ( SELECT elemento ->> 'dsc' AS descr,elemento ->> 'value' AS valor  "
							+ "					         FROM main.params p,  "
							+ "					                jsonb_array_elements(CAST(p.value AS jsonb)) AS elemento   "
							+ "					            WHERE p.paramname = 'FACILITY_YESNO') pr2 ON u.generator = CAST(pr2.valor AS INTEGER) "
							+ "                            LEFT JOIN ( SELECT elemento ->> 'dsc' AS descr,elemento ->> 'value' AS valor  "
							+ "					         FROM main.params p,  "
							+ "					                jsonb_array_elements(CAST(p.value AS jsonb)) AS elemento   "
							+ "					            WHERE p.paramname = 'FACILITY_YESNO') pr3 ON u.gasbackup = CAST(pr3.valor AS INTEGER) "
							+ "                           LEFT JOIN ( SELECT elemento ->> 'dsc' AS descr,elemento ->> 'value' AS valor  "
							+ "					         FROM main.params p,  "
							+ "					                jsonb_array_elements(CAST(p.value AS jsonb)) AS elemento   "
							+ "					            WHERE p.paramname = 'FACILITY_YESNO') pr4 ON u.ups = CAST(pr4.valor AS INTEGER) "
							+ "				         	 LEFT JOIN ( SELECT elemento ->> 'dsc' AS descr,elemento ->> 'value' AS valor  "
							+ "					         FROM main.params p,  "
							+ "					                jsonb_array_elements(CAST(p.value AS jsonb)) AS elemento   "
							+ "					            WHERE p.paramname = 'FACILITY_YESNO') pr5 ON u.ownership = CAST(pr5.valor AS INTEGER) ";
				}
				String QueryTotal = "";
				String name = "u.name"; // buscar por nombre
				String status = "u.status"; // buscar por status
				//String lowername = "LOWER(u.name)"; // se convierte en minúscula
				String lowername = "main.sinacentos(LOWER(u.name))";
				String LowerSearch = paramsService.quitarAcentosJava(searchIn.toLowerCase()); // se convierte en minúscula
                //String f = quitarAcentosJava(LowerSearch);
				// Se verifica si viene dato en el campo search para efectuar la búsqueda
				switch (searchIn) {
				case "": 
					switch (statusIn) {
					case 0:
						// viene sin busqueda por el like
						QueryTotal = SentenciaBase + " WHERE 1 = 1 ";
						

						break;
					case 1:
						// viene sin busqueda por el like
						QueryTotal = SentenciaBase + " WHERE " + status + " = " + 1;
						break;	
					default:
						QueryTotal = SentenciaBase + " WHERE " + status + " = " + 0;
						break;
					}
					break;
				default: // viene con el parametro para buscar por el like
					switch (statusIn) {
					case 0:
						// viene sin busqueda por el like
						QueryTotal = SentenciaBase + " WHERE 1 = 1 ";
						QueryTotal = QueryTotal + " AND ( " + lowername + " LIKE " + "'%" + LowerSearch + "%'" + " )";
						break;
					case 1:
						// viene sin busqueda por el like
						QueryTotal = SentenciaBase + " WHERE " + status + " =  " + 1;
						QueryTotal = QueryTotal + " AND ( " + lowername + " LIKE " + "'%" + LowerSearch + "%'" + " )";
						break;	
					default:
						QueryTotal = SentenciaBase + " WHERE " + status + " =  " + 0;
						QueryTotal = QueryTotal + " AND ( " + lowername + " LIKE " + "'%" + LowerSearch + "%'" + " )";
						break;
					}
					break;
			  }
		 if (formatList==1) {  
				  switch (typeIn) { 
				    case 0:  // Busca por cualquier estatus
				      	QueryTotal = QueryTotal;
				     break;
				    case 1:  // Busca por estatus activo
				    	
				    	QueryTotal = QueryTotal  + " AND " + " u.facilitytypepar " + " = " + typeIn;
				     break;
				    case 2:  // Busca por estatus Inactivo
				    	
				    	//QueryTotal = QueryTotal  + " AND " + status + " = " + searchStatus;
				    	QueryTotal = QueryTotal  + " AND " + " u.facilitytypepar " + " = " + typeIn;
				     break;
				     
	                 case 3:  // Busca por estatus Inactivo
				    	
				    	//QueryTotal = QueryTotal  + " AND " + status + " = " + searchStatus;
				    	QueryTotal = QueryTotal  + " AND " +  " u.facilitytypepar " + " = " + typeIn;
				     break;
				     
	                 case 4:  // Busca por estatus Inactivo
					    	
					    	//QueryTotal = QueryTotal  + " AND " + status + " = " + searchStatus;
					    	QueryTotal = QueryTotal  + " AND " +  " u.facilitytypepar " + " = " + typeIn;
					     break;
					     
	                 case 5:  // Busca por estatus Inactivo
					    	
					    	//QueryTotal = QueryTotal  + " AND " + status + " = " + searchStatus;
					    	QueryTotal = QueryTotal  + " AND " +  " u.facilitytypepar " + " = " + typeIn;
					     break;
					     
	                 case 6:  // Busca por estatus Inactivo
					    	
					    	//QueryTotal = QueryTotal  + " AND " + status + " = " + searchStatus;
					    	QueryTotal = QueryTotal  + " AND " +  " u.facilitytypepar " + " = " + typeIn;
					     break;
					     
	                 case 7:  // Busca por estatus Inactivo
					    	
					    	//QueryTotal = QueryTotal  + " AND " + status + " = " + searchStatus;
					    	QueryTotal = QueryTotal  + " AND " +  " u.facilitytypepar " + " = " + typeIn;
					     break;
					     
	                 case 8:  // Busca por estatus Inactivo
					    	
					    	//QueryTotal = QueryTotal  + " AND " + status + " = " + searchStatus;
					    	QueryTotal = QueryTotal  + " AND " +  " u.facilitytypepar " + " = " + typeIn;
					     break;    
				  
				    default:	// viene con el parametro para buscar por el like		   			    				    	
				    	String var2 = "";
						boolean bloked = false;
						RespuestaMsgDto respuestaDto = new RespuestaMsgDto(var2);
						respuestaDto= new RespuestaMsgDto("Error interno del servidor");
						estatus=HttpStatus.INTERNAL_SERVER_ERROR;   
						return new ResponseEntity(respuestaDto, estatus);
				    	
		         }
		 }	  
				
				// Busca si es ascendente o descendente
		 if (formatList!=2) {  
				switch (orderIn) {
				case 1: // ordena por name y status ascendente
					QueryTotal = QueryTotal + " ORDER BY " + name + " ASC ";
					break;

				case 2:// ordena por name ascendente
					QueryTotal = QueryTotal + " ORDER BY " + status + " ASC ";
					break;

				case 3: // ordena por status ascendente
					QueryTotal = QueryTotal + " ORDER BY " + " u.facilitytypepar "  + " ASC ";
					break;
				case 4: // ordena por status ascendente
					QueryTotal = QueryTotal + " ORDER BY " + " u.certtypepar "  + " ASC ";
					break;
				
				case 5: // ordena por status ascendente
					QueryTotal = QueryTotal + " ORDER BY " + " u.date "  + " ASC ";
					break;
					
				case 6: // ordena por status ascendente
					QueryTotal = QueryTotal + " ORDER BY " + " u.expiration "  + " ASC ";
					break;
					
				case 99: // ordena por status ascendente
					QueryTotal = QueryTotal + " ORDER BY " + " u.id "  + " ASC ";
					break;	

				case -1:// ordena por name y status descendente
					QueryTotal = QueryTotal + " ORDER BY " + name + " DESC ";
					break;

				case -2:// ordena por name descendente
					QueryTotal = QueryTotal + " ORDER BY " + status + " DESC ";
					break;

				case -3:// ordena por status descendente
					QueryTotal = QueryTotal + " ORDER BY " + " u.facilitytypepar "  + " DESC ";
					break;
					
				case -4:// ordena por status descendente
					QueryTotal = QueryTotal + " ORDER BY " + " u.certtypepar "  + " DESC ";
					break;
				
				case -5:// ordena por status descendente
					QueryTotal = QueryTotal + " ORDER BY " + " u.date "  + " DESC ";
					break;
					
				case -6:// ordena por status descendente
					QueryTotal = QueryTotal + " ORDER BY " + " u.expiration "  + " DESC ";
					break;
					
				case -99: // ordena por status ascendente
					QueryTotal = QueryTotal + " ORDER BY " + " u.id "  + " DESC ";
					break;		

				default:
					respuesta.setMsg("Error interno del servidor");
					estatus = HttpStatus.INTERNAL_SERVER_ERROR;
					return new ResponseEntity(respuesta, estatus);
				}
		 } else 
		         {
			 switch (orderIn) {
				case 1: // ordena por name y status ascendente
					QueryTotal = QueryTotal + " ORDER BY " + name + " ASC ";
					break;

				case 2:// ordena por name ascendente
					QueryTotal = QueryTotal + " ORDER BY " + status + " ASC ";
					break;

				case 99: // ordena por status ascendente
					QueryTotal = QueryTotal + " ORDER BY " + " u.id " + " ASC ";
					break;

				case -1:// ordena por name y status descendente
					QueryTotal = QueryTotal + " ORDER BY " + name + " DESC ";
					break;

				case -2:// ordena por name descendente
					QueryTotal = QueryTotal + " ORDER BY " + status + " DESC";
					break;

				case -99:// ordena por status descendente
					QueryTotal = QueryTotal + " ORDER BY " + " u.id " + " DESC";
					break;

				default:
					respuesta.setMsg("Error interno del servidor - indice de orden desconocido");
					estatus = HttpStatus.INTERNAL_SERVER_ERROR;
					return new ResponseEntity(respuesta, estatus);
				}
			 
		         }
				// Se mapea la entidad se le pasa el query y lo bota como un tipo de objeto
				// ParamDto-Buscar en los DTO
				
				
				TypedQuery<FacilitiesResponseDto3> facilities3;
				TypedQuery<FacilitiesResponseDto> facilities;
				List<FacilitiesResponseDto> facilitiesList = new ArrayList();
				List<FacilitiesResponseDto3> facilitiesList3 = new ArrayList();
				
				if (formatList!=2) {
				//	facilities = entityManager.createQuery(QueryTotal,FacilitiesResponseDto.class);
				//	facilitiesList = facilities.getResultList();
				//cuantosregistro = (long) facilities.getResultList().size();
				//facilities.setFirstResult(offsetIn);
				///facilities.setMaxResults(numofrecordsIn);
				

					 QueryTotal = QueryTotal;
			         query = entityManager.createNativeQuery(QueryTotal);
			         cuantosregistro = (long) query.getResultList().size();	
			    

				      // query = entityManager.createNativeQuery(QueryTotal);
				       query.setFirstResult(offsetIn);
					   query.setMaxResults(numofrecordsIn);
					//   listacompleta = query.getResultList();
				
				
				}else {
					facilities3 = entityManager.createQuery(QueryTotal,FacilitiesResponseDto3.class);
					facilitiesList3 = facilities3.getResultList();
					cuantosregistro = (long) facilities3.getResultList().size();
				}

				if (formatList!=2) {
					List<Object[]> listacompleta = query.getResultList();
				// 4. Recorrer la lista y procesar los resultados
				//for (FacilitiesResponseDto faci : facilitiesList) {
			    for (Object[] faci : listacompleta) {	
			    	  //detalleStatus = new StatusDto2();
			    	  StatusDto2 statusDto2= new StatusDto2();
			    	  detalletype = new IddscDto();
					  detalleCertifi  = new IddscDto();
					  detalleGenerator  = new IddscDto();
					  detalleGas = new IddscDto();
					  detalleUps = new IddscDto();
					  detalleOwner = new IddscDto();
					  
					facilitiesResponseDto.setId((int) faci[0]);
					facilitiesResponseDto.setName((String) faci[1]);
					facilitiesResponseDto.setAddress((String) faci[4]);
					facilitiesResponseDto.setDate((String) faci[9]);
					facilitiesResponseDto.setExpiration((String) faci[10]);
					facilitiesResponseDto.setCountry((String) faci[11]);
					facilitiesResponseDto.setRegion((String) faci[12]);
					
					//seteando el estatus
					statusDto2.setId((int) faci[2]);
					statusDto2.setName((String) faci[3]);
					facilitiesResponseDto.setStatus(statusDto2);
					// fin seteo estatus
					
					//seteando el type
		         	try {		
				   	  int facitilytype  = Integer.parseInt((String) faci[5]);
					    detalletype.setId(facitilytype);
					    detalletype.setDsc((String) faci[6]);
					    facilitiesResponseDto.setType(detalletype);
			         }  catch (Exception e) { 
			        	 detalletype.setId(0);
						 detalletype.setDsc("");
						 facilitiesResponseDto.setType(detalletype);
			       }
					//fin seteo type
					
					//seteando la certificacion
			     try {		
					    int certifitype  = Integer.parseInt((String) faci[7]);
					    detalleCertifi.setId(certifitype);
				     	detalleCertifi.setDsc((String) faci[8]);
					    facilitiesResponseDto.setCertification(detalleCertifi);
					
			        }  catch (Exception e) { 
			        	detalleCertifi.setId(0);
						detalleCertifi.setDsc("");
						facilitiesResponseDto.setCertification(detalleCertifi);   
			        }
					//fin seteo certififacion
					
					
					//seteando el generator
					try {
					    int generatype  = Integer.parseInt((String) faci[13]);
				   	    detalleGenerator.setId(generatype);
					    detalleGenerator.setDsc((String) faci[14]);
					    facilitiesResponseDto.setGenerator(detalleGenerator);
					
			           }  catch (Exception e) { 
			        	    detalleGenerator.setId(0);
						    detalleGenerator.setDsc("");
						    facilitiesResponseDto.setGenerator(detalleGenerator);
			         }
				 	// fin del seteo generator
					
					//seteando el gasbackup
					try {
					   int gasbackuptype  = Integer.parseInt((String) faci[15]);
					      detalleGas.setId(gasbackuptype);
						  detalleGas.setDsc((String) faci[16]);
						  facilitiesResponseDto.setGasbackup(detalleGas); 
			         }  catch (Exception e) {
					      detalleGas.setId(0);
					       detalleGas.setDsc("");
					     facilitiesResponseDto.setGasbackup(detalleGas);
			         }
					// fin del seteo gasbackup
					
					//seteando el ups
					try {
					   int upstype  = Integer.parseInt((String) faci[17]);
					    detalleUps.setId(upstype);
				     	detalleUps.setDsc((String) faci[18]);
				 	    facilitiesResponseDto.setUps(detalleUps);  
			           }  catch (Exception e) { 
					    detalleUps.setId(0);
				     	detalleUps.setDsc("");
				     	 facilitiesResponseDto.setUps(detalleUps);  
			           }
					// fin del seteo ups
					
					//seteando el ownership
					try {
					   int detalleOwnertype  = Integer.parseInt((String) faci[19]);
					        detalleOwner.setId(detalleOwnertype);
					        detalleOwner.setDsc((String) faci[20]);
				 	    facilitiesResponseDto.setOwnership(detalleOwner);   
			           }  catch (Exception e) { 
			        	   detalleOwner.setId(0);
			        	   detalleOwner.setDsc("");
			        	   facilitiesResponseDto.setOwnership(detalleOwner);
			           }
					// fin del seteo ownership
					
					facilitiesResultado.add(facilitiesResponseDto);
					facilitiesResponseDto = new FacilitiesResponseDto();
				}

			    detallePrivilege = new PrivilegesAllDto();
	    	       boolean tieneView = rolesPrivilegesRepository.existsByRolidAndPrivilegeid(idrol,480);
				   boolean tieneUpdate = rolesPrivilegesRepository.existsByRolidAndPrivilegeid(idrol,481);
				   boolean tieneAdd = rolesPrivilegesRepository.existsByRolidAndPrivilegeid(idrol,482);
				   boolean tieneDelete = rolesPrivilegesRepository.existsByRolidAndPrivilegeid(idrol,483);
				   //existsByRolidAndPrivilegeid
				   
   	    	 	    detallePrivilege.setView(tieneView);
		    	  	detallePrivilege.setUpdate(tieneUpdate);		    	  
		    	  	detallePrivilege.setAdd(tieneAdd);
		    	  	detallePrivilege.setDelete(tieneDelete);
		    	  	
		    	  	 String SetenciaTypes="";
		    	  
					 
				      SetenciaTypes= "SELECT  elemento ->> 'dsc' AS descr,elemento ->> 'value' AS valor "
				 		+ " FROM main.params p, jsonb_array_elements(CAST(p.value AS jsonb)) AS elemento WHERE paramname = 'FACILITY_TYPE' ORDER BY valor ASC";
				      
				      Query queryTypes = entityManager.createNativeQuery(SetenciaTypes);
				       List<Object[]> listatipos= queryTypes.getResultList();
				       for (Object[] types : listatipos) {
				    	   detalleTypes = new TypesUnitDto();
				    	  
				    	   detalleTypes.setDsc((String) types[0]);
				    	   detalleTypes.setValue((String) types[1]);
				    	   listasTypes.add(detalleTypes);
				       }
			

				facili.setNumofrecords(cuantosregistro);
				facili.setRecords(facilitiesResultado);
				facili.setSessionvalidthru(fechaComoCadena);
				facili.setTypes(listasTypes);
				facili.setPrivileges(detallePrivilege);
				return new ResponseEntity(facili, HttpStatus.OK);
					
				} else {
					
					// 4. Recorrer la lista y procesar los resultados formato2
					StatusDto2 statusDto2= new StatusDto2();
					for (FacilitiesResponseDto3 faci : facilitiesList3) {
						 statusDto2= new StatusDto2();
						facilitiesResponseDto2.setId(faci.getId());
						facilitiesResponseDto2.setName(faci.getName());
						statusDto2.setId(faci.getIdStatus());
						statusDto2.setName(faci.getDecstatus());
						facilitiesResponseDto2.setStatus(statusDto2);
						facilitiesResultado2.add(facilitiesResponseDto2);
						facilitiesResponseDto2 = new FacilitiesResponseDto2();
					}
					
					facili2.setRecords(facilitiesResultado2);
					facili2.setSessionvalidthru(fechaComoCadena);
					return new ResponseEntity(facili2, HttpStatus.OK);
				}
				
			} catch (Exception e) {
				respuesta.setMsg("Error interno del servidor ");
				estatus = HttpStatus.INTERNAL_SERVER_ERROR;
			} finally {
		        if (entityManager != null && entityManager.isOpen()) {
		            entityManager.close();
		        }
		    }
		}
		return new ResponseEntity(respuesta, HttpStatus.OK);
	}
	
	
		
		@GetMapping("/facilities/{facilityid}")
		public ResponseEntity<?> getOneFacilities(HttpServletRequest request, @PathVariable("facilityid") final Integer facilityid) throws ParseException {
		RespuestaMsgDto respuesta = new RespuestaMsgDto("");
		HttpStatus estatus = HttpStatus.FORBIDDEN;
		long cuantosregistro = 0;

		String sessionid = request.getHeader("Authorization");
		Date fecha = new Date();
		SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		String dataFormattata = formatter.format(fecha);

		String searchIn = "";
		int statusIn = 0;
		String searchModule = "";
		String searchUsr = "";
		String contentIn = "";
		int orderIn = 0;
		int offsetIn = 0;
		int numofrecordsIn = 0;
		int formatList=0;
		 int typeIn=0;
		 int idrol;
		 IddscDto detalletype = new IddscDto();
		 IddscDto detalleCertifi = new IddscDto();
		 IddscDto detalleGenerator = new IddscDto();
		 IddscDto detalleGas = new IddscDto();
		 IddscDto detalleUps = new IddscDto();
		 IddscDto detalleOwner = new IddscDto();
			TypesUnitDto detalleTypes;
			TypesUnitDto detalleyesno;
			TypesUnitDto detallecertificacion;
    	  	List<TypesUnitDto> listasTypes = new ArrayList<>();
    	  	List<TypesUnitDto> listasYesno = new ArrayList<>();
    	  	List<TypesUnitDto> listasCertificacion = new ArrayList<>();
		Optional<Params> deSessDuration = paramsRepository.findByParamname("SESSION_DURATION");
		String SessionDuration = deSessDuration.get().getValue();
		int duracionSession = Integer.parseInt(SessionDuration);
		Date fecha2 = new Date();
		Calendar calendar = Calendar.getInstance();
		calendar.setTime(fecha2); // tuFechaBase es un Date;
		// calendar.add(Calendar.MINUTE, minutosASumar); //minutosASumar es int.
		calendar.add(Calendar.MINUTE, duracionSession); // horasASumar es int.
		// lo que más quieras sumar
		Date ValidThrufechaSalida = calendar.getTime(); // Y ya tienes la fecha sumada.
		SimpleDateFormat salida = new SimpleDateFormat("yyyy-MM-dd HH:mm"); // 2024-12-23 23:00
		String fechaComoCadena = salida.format(ValidThrufechaSalida);
		System.out.println(fechaComoCadena);

		// Verifico la session
		if (sessionid == null) {
			respuesta.setMsg("Llamada al servicio malformado");
			estatus = HttpStatus.BAD_REQUEST;
			return new ResponseEntity(respuesta, estatus);
		} else {
			sessionid = sessionid.substring(7);
			// verifico si la sesión del usuario existe.
			Optional<Users> encontreSessionUsuario = usersRepository.getBySessionid(sessionid);
			if (encontreSessionUsuario.isPresent()) { // si la sesión del usuario existe
				Date FechaReg = encontreSessionUsuario.get().getValidthru();
				// Llamada a la funcion que validad el tiempo de Session, retorna la fecha
				// sumandole el tiempo de session activa, y vacio si no esta activa
				fechaComoCadena = securityService.consultarSessionActiva(FechaReg, fecha2,
						encontreSessionUsuario.get().getId());

				if (fechaComoCadena == "") {
					RespuestaMsgDto respuestaDto2;
					String var2 = "";
					boolean bloked2 = false;
					respuestaDto2 = new RespuestaMsgDto(var2);
					respuestaDto2.setMsg("Sesión expirada o inválida");
					return new ResponseEntity(respuestaDto2, HttpStatus.UNAUTHORIZED);
				}

				// Este proceso permite obtener un listado de los procesos. (Priv 120)
				//formatList = tiposfiltros.getFormat();
				int rolisvalid = 0;
				Roles roles = encontreSessionUsuario.get().getRolid();
				idrol = roles.getId();
				rolisvalid = auditRepository.getCantbyRolAndPrivi(encontreSessionUsuario.get().getRolid().getId(), 480);
				//  formatList = tiposfiltros.getFormat();
			
				    if (rolisvalid==0) {
					respuesta.setMsg("No tiene los Privilegios");
					estatus = HttpStatus.FORBIDDEN;
					return new ResponseEntity(respuesta, estatus);
				  }
				  

			
				
				
				    
				// Verifico los Shorcouts
				if (contentIn != null && contentIn != "") {
					menuService.iscontentdiffnull(contentIn, encontreSessionUsuario.get().getId());
				}

			} else { // Si la sesión que viene es inválida
				respuesta.setMsg("Sesión expirada o inválida");
				estatus = HttpStatus.BAD_REQUEST;
				return new ResponseEntity(respuesta, estatus);
			}

			// Aqui empieza la carga de la data de respuesta

			FacilitiesEntryDto facili = new FacilitiesEntryDto();
			FacilitResponseDto2 facili2 = new FacilitResponseDto2();
			FacilitiesResponseDto facilitiesResponseDto = new FacilitiesResponseDto();
			FacilitiesResponseDto2 facilitiesResponseDto2 = new FacilitiesResponseDto2();
			FacilitiesResponseDto3 facilitiesResponseDto3 = new FacilitiesResponseDto3();
			PrivilegesAllDto detallePrivilege = new PrivilegesAllDto();
			List<FacilitiesResponseDto> facilitiesResultado = new ArrayList();

			List<FacilitiesResponseDto2> facilitiesResultado2 = new ArrayList();
			Query query = null;
			try {
				// Sentencia General
				String SentenciaBase="";
				
					SentenciaBase = " SELECT u.id,u.name,u.status,CASE WHEN u.status = 1 THEN 'Activo' ELSE 'Inactivo' END AS estatus,u.address, "
							+ " CAST(u.facilitytypepar AS TEXT) AS facilitytypepar,pr.descr AS desctype,CAST(u.certtypepar AS TEXT) AS certtypepar,pr1.descr AS desccerty,"
							+ " SUBSTRING(CAST(u.date AS TEXT),1,10) AS dated,SUBSTRING(CAST(u.expiration AS TEXT),1,10) AS expiration,u.country,u.region,"
							+ " CAST(u.generator AS TEXT) AS generator,pr2.descr as descgene,"
							+ " CAST(u.gasbackup AS TEXT) AS gasbackup,pr3.descr as descgas,"
							+ " CAST(u.ups AS TEXT) AS ups,pr4.descr as descups,"
							+ " CAST(u.ownership AS TEXT) AS ownership,pr5.descr as descowner"
							+ "					        FROM  main.Facilities u  "
							+ "					       LEFT JOIN ( SELECT elemento ->> 'dsc' AS descr,elemento ->> 'value' AS valor  "
							+ "					         FROM main.params p,  "
							+ "					             jsonb_array_elements(CAST(p.value AS jsonb)) AS elemento  "
							+ "					         WHERE p.paramname = 'FACILITY_TYPE') pr ON u.facilitytypepar = CAST(pr.valor AS INTEGER)  "
							+ "					         LEFT JOIN ( SELECT elemento ->> 'dsc' AS descr,elemento ->> 'value' AS valor  "
							+ "					         FROM main.params p,  "
							+ "					                jsonb_array_elements(CAST(p.value AS jsonb)) AS elemento   "
							+ "					            WHERE p.paramname = 'CERTIFICATION_TYPE') pr1 ON u.certtypepar = CAST(pr1.valor AS INTEGER)  "
							+ "                            LEFT JOIN ( SELECT elemento ->> 'dsc' AS descr,elemento ->> 'value' AS valor  "
							+ "					         FROM main.params p,  "
							+ "					                jsonb_array_elements(CAST(p.value AS jsonb)) AS elemento   "
							+ "					            WHERE p.paramname = 'FACILITY_YESNO') pr2 ON u.generator = CAST(pr2.valor AS INTEGER) "
							+ "                            LEFT JOIN ( SELECT elemento ->> 'dsc' AS descr,elemento ->> 'value' AS valor  "
							+ "					         FROM main.params p,  "
							+ "					                jsonb_array_elements(CAST(p.value AS jsonb)) AS elemento   "
							+ "					            WHERE p.paramname = 'FACILITY_YESNO') pr3 ON u.gasbackup = CAST(pr3.valor AS INTEGER) "
							+ "                           LEFT JOIN ( SELECT elemento ->> 'dsc' AS descr,elemento ->> 'value' AS valor  "
							+ "					         FROM main.params p,  "
							+ "					                jsonb_array_elements(CAST(p.value AS jsonb)) AS elemento   "
							+ "					            WHERE p.paramname = 'FACILITY_YESNO') pr4 ON u.ups = CAST(pr4.valor AS INTEGER) "
							+ "				         	 LEFT JOIN ( SELECT elemento ->> 'dsc' AS descr,elemento ->> 'value' AS valor  "
							+ "					         FROM main.params p,  "
							+ "					                jsonb_array_elements(CAST(p.value AS jsonb)) AS elemento   "
							+ "					            WHERE p.paramname = 'FACILITY_YESNO') pr5 ON u.ownership = CAST(pr5.valor AS INTEGER) "
							+ " WHERE u.id = " + facilityid;
				
					
				String QueryTotal = SentenciaBase;
				
				
				
				//TypedQuery<FacilitiesResponseDto3> facilities3;
			//	TypedQuery<FacilitiesResponseDto> facilities;
				List<FacilitiesResponseDto> facilitiesList = new ArrayList();
				List<FacilitiesResponseDto3> facilitiesList3 = new ArrayList();
				
			
			

					// QueryTotal = QueryTotal;
			         query = entityManager.createNativeQuery(QueryTotal);
			         cuantosregistro = (long) query.getResultList().size();	
					 List<Object[]> listacompleta = query.getResultList();
				// 4. Recorrer la lista y procesar los resultados
				//for (FacilitiesResponseDto faci : facilitiesList) {
			    for (Object[] faci : listacompleta) {	
			    	  //detalleStatus = new StatusDto2();
			    	  StatusDto2 statusDto2= new StatusDto2();
			    	  detalletype = new IddscDto();
					  detalleCertifi  = new IddscDto();
					  detalleGenerator  = new IddscDto();
					  detalleGas = new IddscDto();
					  detalleUps = new IddscDto();
					  detalleOwner = new IddscDto();
					  
					facilitiesResponseDto.setId((int) faci[0]);
					facilitiesResponseDto.setName((String) faci[1]);
					facilitiesResponseDto.setAddress((String) faci[4]);
					facilitiesResponseDto.setDate((String) faci[9]);
					facilitiesResponseDto.setExpiration((String) faci[10]);
					facilitiesResponseDto.setCountry((String) faci[11]);
					facilitiesResponseDto.setRegion((String) faci[12]);
					
					//seteando el estatus
					statusDto2.setId((int) faci[2]);
					statusDto2.setName((String) faci[3]);
					facilitiesResponseDto.setStatus(statusDto2);
					// fin seteo estatus
					
					//seteando el type
		         	try {		
				   	  int facitilytype  = Integer.parseInt((String) faci[5]);
					    detalletype.setId(facitilytype);
					    detalletype.setDsc((String) faci[6]);
					    facilitiesResponseDto.setType(detalletype);
			         }  catch (Exception e) { 
			        	 detalletype.setId(0);
						 detalletype.setDsc("");
						 facilitiesResponseDto.setType(detalletype);
			       }
					//fin seteo type
					
					//seteando la certificacion
			     try {		
					    int certifitype  = Integer.parseInt((String) faci[7]);
					    detalleCertifi.setId(certifitype);
				     	detalleCertifi.setDsc((String) faci[8]);
					    facilitiesResponseDto.setCertification(detalleCertifi);
					
			        }  catch (Exception e) { 
			        	detalleCertifi.setId(0);
						detalleCertifi.setDsc("");
						facilitiesResponseDto.setCertification(detalleCertifi);   
			        }
					//fin seteo certififacion
					
					
					//seteando el generator
					try {
					    int generatype  = Integer.parseInt((String) faci[13]);
				   	    detalleGenerator.setId(generatype);
					    detalleGenerator.setDsc((String) faci[14]);
					    facilitiesResponseDto.setGenerator(detalleGenerator);
					
			           }  catch (Exception e) { 
			        	    detalleGenerator.setId(0);
						    detalleGenerator.setDsc("");
						    facilitiesResponseDto.setGenerator(detalleGenerator);
			         }
				 	// fin del seteo generator
					
					//seteando el gasbackup
					try {
					   int gasbackuptype  = Integer.parseInt((String) faci[15]);
					      detalleGas.setId(gasbackuptype);
						  detalleGas.setDsc((String) faci[16]);
						  facilitiesResponseDto.setGasbackup(detalleGas); 
			         }  catch (Exception e) {
					      detalleGas.setId(0);
					       detalleGas.setDsc("");
					     facilitiesResponseDto.setGasbackup(detalleGas);
			         }
					// fin del seteo gasbackup
					
					//seteando el ups
					try {
					   int upstype  = Integer.parseInt((String) faci[17]);
					    detalleUps.setId(upstype);
				     	detalleUps.setDsc((String) faci[18]);
				 	    facilitiesResponseDto.setUps(detalleUps);  
			           }  catch (Exception e) { 
					    detalleUps.setId(0);
				     	detalleUps.setDsc("");
				     	 facilitiesResponseDto.setUps(detalleUps);  
			           }
					// fin del seteo ups
					
					//seteando el ownership
					try {
					   int detalleOwnertype  = Integer.parseInt((String) faci[19]);
					        detalleOwner.setId(detalleOwnertype);
					        detalleOwner.setDsc((String) faci[20]);
				 	    facilitiesResponseDto.setOwnership(detalleOwner);   
			           }  catch (Exception e) { 
			        	   detalleOwner.setId(0);
			        	   detalleOwner.setDsc("");
			        	   facilitiesResponseDto.setOwnership(detalleOwner);
			           }
					// fin del seteo ownership
					
					//facilitiesResultado.add(facilitiesResponseDto);
					//facilitiesResponseDto = new FacilitiesResponseDto();
				}

			     // seteando los tipos de instalaciones
		    	  	 String SetenciaTypes="";
				      SetenciaTypes= "SELECT  elemento ->> 'dsc' AS descr,elemento ->> 'value' AS valor "
				 		+ " FROM main.params p, jsonb_array_elements(CAST(p.value AS jsonb)) AS elemento WHERE paramname = 'FACILITY_TYPE' ORDER BY valor ASC";
				      
				      Query queryTypes = entityManager.createNativeQuery(SetenciaTypes);
				       List<Object[]> listatipos= queryTypes.getResultList();
				       for (Object[] types : listatipos) {
				    	   detalleTypes = new TypesUnitDto();
				    	  
				    	   detalleTypes.setDsc((String) types[0]);
				    	   detalleTypes.setValue((String) types[1]);
				    	   listasTypes.add(detalleTypes);
				       }
			   /// fin seteo instalaciones
				       
				   /// seteando los yes no 
		    	  	
		    		 String SetenciaYesno="";
		    		    SetenciaYesno= "SELECT  elemento ->> 'dsc' AS descr,elemento ->> 'value' AS valor "
				 		+ " FROM main.params p, jsonb_array_elements(CAST(p.value AS jsonb)) AS elemento WHERE paramname = 'FACILITY_YESNO' ORDER BY "
				 		+ "   CASE (elemento ->> 'value') "
				 		+ "        WHEN '-1' THEN 1 "
				 		+ "        WHEN '1' THEN 2 "
				 		+ "        WHEN '2' THEN 3 "
				 		+ "        ELSE 4 "
				 		+ "    END, "
				 		+ "    valor ASC ";
				      
				      Query queryYesno = entityManager.createNativeQuery(SetenciaYesno);
				       List<Object[]> listayesno= queryYesno.getResultList();
				       for (Object[] yesno : listayesno) {
				    	   detalleyesno = new TypesUnitDto();
				    	  
				    	   detalleyesno.setDsc((String) yesno[0]);
				    	   detalleyesno.setValue((String) yesno[1]);
				    	   listasYesno.add(detalleyesno);
				       }
				   // fin del seteo de los yesno    
				       
				   // seteando los cetrtificados
				     //  TypesUnitDto detallecertificacion;
			    	  //	List<TypesUnitDto> listasCertificacion = new ArrayList<>();
			    	  	
			    	  	 String SetenciaCer="";
			    	  	SetenciaCer= "SELECT  elemento ->> 'dsc' AS descr,elemento ->> 'value' AS valor "
					 		+ " FROM main.params p, jsonb_array_elements(CAST(p.value AS jsonb)) AS elemento WHERE paramname = 'CERTIFICATION_TYPE' ORDER BY valor ASC";
					      
					      Query queryCer = entityManager.createNativeQuery(SetenciaCer);
					       List<Object[]> listaCer= queryCer.getResultList();
					       for (Object[] certi : listaCer) {
					    	   detallecertificacion = new TypesUnitDto();
					    	  
					    	   detallecertificacion.setDsc((String) certi[0]);
					    	   detallecertificacion.setValue((String) certi[1]);
					    	   listasCertificacion.add(detallecertificacion);
					       }
			    	  	
				    //fin setei certificados   

			
				facili.setTypes(listasTypes);
				facili.setYesno(listasYesno);
				facili.setCertification(listasCertificacion);
				facili.setEntry(facilitiesResponseDto);
				
				return new ResponseEntity(facili, HttpStatus.OK);
					
			
			} catch (Exception e) {
				respuesta.setMsg("Error interno del servidor ");
				estatus = HttpStatus.INTERNAL_SERVER_ERROR;
			} finally {
		        if (entityManager != null && entityManager.isOpen()) {
		            entityManager.close();
		        }
		    }
		}
		return new ResponseEntity(respuesta, HttpStatus.OK);
	}
		
		@PostMapping("/facilities/{facilityid}")
		public ResponseEntity<ParamsResponseDto> FacilitesUpdate(HttpServletRequest request,@RequestBody FacilitiesRequestDto datosvp,@PathVariable("facilityid") final Integer facilityid) throws ParseException {
				//@GetMapping("/vicepresidencies/{vicepresidencyid}")
				
				RespuestaValueDto respuestaValueDto;
				RespuestaMsgDto respuesta = new RespuestaMsgDto("");
				HttpStatus estatus = HttpStatus.FORBIDDEN;
				ParamsResponseDto paramsResponseDto = new ParamsResponseDto();
				ParamsDto detalleParams;
				PrivilegesDto detallePrivilege;
			     List<ParamsDto> listasParams = new ArrayList<>();
			     List<PrivilegesDto> listasPrivelege = new ArrayList<>();
			     
				 int idparametro = facilityid;
				 
				 int valor = idparametro;
				 String sessionid = request.getHeader("Authorization");
				  Date fecha = new Date();
				    SimpleDateFormat  formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			        String dataFormattata = formatter.format(fecha);
			        Date fechaDate = formatter.parse(dataFormattata);
			        AuditRequestDto  auditDto=new AuditRequestDto();
			        Optional<Users> encontreSessionUsuario;    	       	  		
				   Date fecha2 = new Date();
				   Calendar calendar = Calendar.getInstance();
			
				 
					if (sessionid==null) {
						String var = "";
						boolean bloked = false;
						RespuestaMsgDto respuestaDto = new RespuestaMsgDto(var);
						//respuestaDto.setBlocked(bloked);
						respuestaDto.setMsg("Llamada al servicio malformado");
						//Error 400
						return new ResponseEntity(respuestaDto, HttpStatus.BAD_REQUEST);
					} else   {
						 
						   sessionid = sessionid.substring(7);
						   encontreSessionUsuario =usersRepository.getBySessionid(sessionid);
					       String fechaComoCadena;
						   
						   if (encontreSessionUsuario.isPresent()) {
							   
							   Date FechaReg = encontreSessionUsuario.get().getValidthru(); 
		  					   //Llamada a la funcion que validad el tiempo de Session, retorna la fecha sumandole el tiempo de session activa, y vacio si no esta activa
		  					   
		  					  //  fechaComoCadena  = securityService.consultarSessionActiva(FechaReg,fecha2);
		  					   fechaComoCadena  = securityService.consultarSessionActiva(FechaReg,fecha2,encontreSessionUsuario.get().getId());
		  					    if (fechaComoCadena=="") {
		  						   
		  						   
		  						   
		  						   String var = "";
		  							boolean bloked = false;
		  							RespuestaMsgDto respuestaDto = new RespuestaMsgDto(var);
		  							//respuestaDto.setBlocked(bloked);
		  							respuestaDto.setMsg("Sesión expirada o inválida"); 
		  							return new ResponseEntity(respuestaDto, HttpStatus.UNAUTHORIZED);
		  						   
		  					    }
		  					   
							 //Actualiza o Incluye un registro de un usuario. (Si el unitid es 0 se incluye). (priv 111 MOD Y 112 INC)
							   if (idparametro==0) {
								   //el permiso es el 632
								   Roles roles = encontreSessionUsuario.get().getRolid();
								   int idrol = roles.getId();
								   int rolisvalid = auditRepository.getCantbyRolAndPrivi(idrol, 482);
								 //  rolisvalid = 3;
								   if (rolisvalid==0) {
									   
									   String var = "";
										boolean bloked = false;
										RespuestaMsgDto respuestaDto = new RespuestaMsgDto(var);
										//respuestaDto.setBlocked(bloked);
										respuestaDto.setMsg("No tiene los Privilegios"); 
										return new ResponseEntity(respuestaDto, HttpStatus.FORBIDDEN);
									   
								     }
								
								   
							   } else {
							   
							   Roles roles = encontreSessionUsuario.get().getRolid();
							   int idrol = roles.getId();
							   int rolisvalid = auditRepository.getCantbyRolAndPrivi(idrol, 481);
							   //rolisvalid = 3;
							   if (rolisvalid==0) {
								   
								   String var = "";
									boolean bloked = false;
									RespuestaMsgDto respuestaDto = new RespuestaMsgDto(var);
									//respuestaDto.setBlocked(bloked);
									respuestaDto.setMsg("No tiene los Privilegios"); 
									return new ResponseEntity(respuestaDto, HttpStatus.FORBIDDEN);
								   
							     }
							   
	                               boolean existeFac = facilitiesRepository.existsById(idparametro);
							   
							      if  (!existeFac) {	
								   
								  
								    
								    	String var = "";
								    	RespuestaMsgDto respuestaDto = new RespuestaMsgDto(var);
										//respuestaDto.setBlocked(bloked);
										respuestaDto.setMsg("Registro No encontrado");
										//Error 400
										return new ResponseEntity(respuestaDto, HttpStatus.BAD_REQUEST);
								    
							       }
							   } 
							   						                        						 							
							   
							   if (idparametro==0) {
								   
		                
		                       
		                       if  (datosvp.getName()!= "" ) {	
								   
								   //boolean existeName = unitsRepository.existsByName(datosUnidad.getName());
		                    	   String Query2 = "SELECT name FROM main.facilities WHERE LOWER(name) = " + "'" + datosvp.getName().toLowerCase() + "'";
		                    	   
								   Long cuantosregistroname = (long) jdbcTemplate.queryForList(Query2).size();
								   
								    if (cuantosregistroname>0) {
								    	String var = "";
								    	RespuestaMsgDto respuestaDto = new RespuestaMsgDto(var);
										//respuestaDto.setBlocked(bloked);
										respuestaDto.setMsg("Registro Duplicado");
										//Error 40
										return new ResponseEntity(respuestaDto, HttpStatus.CONFLICT);
								    }
							     }						                     						   											
								   
							   }
								   
							       
					
						   
						 } else {
								String var = "";
								boolean bloked = false;
								RespuestaMsgDto respuestaDto = new RespuestaMsgDto(var);
								//respuestaDto.setBlocked(bloked);
								respuestaDto.setMsg("Sesión expirada o inválida");
								//Error 400
								return new ResponseEntity(respuestaDto, HttpStatus.UNAUTHORIZED);
						 }
					}
					
					
				
				try {
					
					
					Facilities tipofaci2=null;
					Facilities tipofaci=null;
					Facilities tipofaciNew2=null;
					Optional<Facilities> nuevoinsertado = null;
					
					
					if (idparametro==0) {
						
						Facilities tipofaciNew = new Facilities();
						
						
						tipofaciNew.setStatus(datosvp.getStatus());
						tipofaciNew.setModifiedat(fechaDate);
						tipofaciNew.setCreatedat(fechaDate); 
						tipofaciNew.setName(datosvp.getName());
						int idfacilitytypepar  = Integer.parseInt(datosvp.getType());
						tipofaciNew.setFacilitytypepar(idfacilitytypepar);
						int idCertitypepar  = Integer.parseInt(datosvp.getCertification());
						tipofaciNew.setCerttypepar(idCertitypepar);
						tipofaciNew.setCountry(datosvp.getCountry());
						tipofaciNew.setRegion(datosvp.getRegion());
						tipofaciNew.setDate(datosvp.getDate());
						tipofaciNew.setExpiration(datosvp.getExpiration());
						tipofaciNew.setGenerator(datosvp.getGenerator());
						tipofaciNew.setGasbackup(datosvp.getGasbackup());
						tipofaciNew.setUps(datosvp.getUps());
						tipofaciNew.setOwnership(datosvp.getOwnership());
						tipofaciNew.setAddress(datosvp.getAddress());											
				        
						tipofaciNew2=facilitiesService.addIdFacilities(tipofaciNew);
						tipofaci2 = tipofaciNew2;
				        nuevoinsertado = facilitiesRepository.findByName(datosvp.getName());
						int idInsertado =  nuevoinsertado.get().getId();
						int idmensaje = idInsertado;

					    //////////////////////////INSERCION BLOQUE DE AUDITORIA///////////////////
					     String module = "Instalaciones";
					     //String Descmodule = "Actualización de parametro del Sistema con id: " + parmid  ;
					     String Descmodule = "Se agregó la Instalación: " + datosvp.getName() + " con Id:" + idInsertado ;
					    
				         auditDto.setIpaddr(HttpReqRespUtils.getClientIpAddressIfServletRequestExist());			        
				         
				         String singo1 = "(";
				         String singo2 = ")";
				         String usryemail = encontreSessionUsuario.get().getUsr().concat(" ").concat(singo1).concat(encontreSessionUsuario.get().getEmail().concat(singo2));
				         auditDto.setUserref(usryemail);
				         auditDto.setModule(module);
				         auditDto.setDesc(Descmodule);
				         auditDto.setCreatedat(fechaDate);
				 		   usersService.registrarAuditSesion(auditDto); 
				 		   
				 		
							respuestaValueDto= new RespuestaValueDto(idmensaje);
							estatus=HttpStatus.OK;
							return new ResponseEntity(respuestaValueDto, estatus); 
			         

					} else {
						 //tipoUsers = usersService.getUsersByid(idparametro);
						    /// tipoUnits = workersService.getWorkersByid(idparametro);
					    	tipofaci = facilitiesService.getFacilitiesByid(idparametro);
						    // Positions relaposition = positionsRepository.getById(datosWorker.getPositionid());
						 
					    	tipofaci.setStatus(datosvp.getStatus());
					    	tipofaci.setModifiedat(fechaDate);
					    	//tipofaci.setCreatedat(fechaDate); 
					    	//tipofaci.setName(datosvp.getName());
							int idfacilitytypepar  = Integer.parseInt(datosvp.getType());
							tipofaci.setFacilitytypepar(idfacilitytypepar);
							int idCertitypepar  = Integer.parseInt(datosvp.getCertification());
							tipofaci.setCerttypepar(idCertitypepar);
							tipofaci.setCountry(datosvp.getCountry());
							tipofaci.setRegion(datosvp.getRegion());
							tipofaci.setDate(datosvp.getDate());
							tipofaci.setExpiration(datosvp.getExpiration());
							tipofaci.setGenerator(datosvp.getGenerator());
							tipofaci.setGasbackup(datosvp.getGasbackup());
							tipofaci.setUps(datosvp.getUps());
							tipofaci.setOwnership(datosvp.getOwnership());
							tipofaci.setAddress(datosvp.getAddress());									
						

							String vp1 = tipofaci.getName();
							String vp2 = datosvp.getName();
							if (vp1.equals(vp2)){
								String Validausers = "La Instalacion es la misma";
						    	
							} else {
						
							 String QueryTotal = "SELECT name FROM main.facilities WHERE LOWER(name) = " + "'" + datosvp.getName().toString().toLowerCase() + "'" ;
							 Long validavp = (long) jdbcTemplate.queryForList(QueryTotal).size();
							 
			                if (validavp>0) {
								
								String var = "";
								//boolean bloked = false;
								RespuestaMsgDto respuestaDto = new RespuestaMsgDto(var);
								//respuestaDto.setBlocked(bloked);
								respuestaDto.setMsg("Registro Duplicado");
								//Error 400
								return new ResponseEntity(respuestaDto, HttpStatus.CONFLICT);
								
							} else {
								tipofaci.setName(datosvp.getName());
							}
						}																
						
															
				          
							tipofaci2=facilitiesService.addIdFacilities(tipofaci);
							
						    //////////////////////////INSERCION BLOQUE DE AUDITORIA///////////////////
						     String module = "Instalaciones";
						     //String Descmodule = "Actualización de parametro del Sistema con id: " + parmid  ;
						     String Descmodule = "Se actualizó la Instalación: "+ datosvp.getName() + " con Id:" + facilityid ;
						    
					         auditDto.setIpaddr(HttpReqRespUtils.getClientIpAddressIfServletRequestExist());			        
					         
					         String singo1 = "(";
					         String singo2 = ")";
					         String usryemail = encontreSessionUsuario.get().getUsr().concat(" ").concat(singo1).concat(encontreSessionUsuario.get().getEmail().concat(singo2));
					         auditDto.setUserref(usryemail);
					         auditDto.setModule(module);
					         auditDto.setDesc(Descmodule);
					         auditDto.setCreatedat(fechaDate);
					 		   usersService.registrarAuditSesion(auditDto); 
					 		  //////////////////////////INSERCION BLOQUE DE AUDITORIA///////////////////	
					 		   int idmensaje = facilityid;
					 		   respuestaValueDto= new RespuestaValueDto(idmensaje);
								estatus=HttpStatus.OK;
								return new ResponseEntity(respuestaValueDto, estatus); 
				         
				      
					      }
				
				} catch (Exception e) {
		            // Manejo de excepciones
					respuesta= new RespuestaMsgDto("Error interno del servidor");
					estatus=HttpStatus.INTERNAL_SERVER_ERROR;            
		        } finally {
					if (entityManager != null && entityManager.isOpen()) {
						entityManager.close();
					}
				}
				
				return new ResponseEntity(respuesta, estatus);
			
			}	
		
		
		@DeleteMapping("/facilities/{facilityid}")
		public ResponseEntity<?> borrarWorkers(HttpServletRequest request, @PathVariable("facilityid") final Integer facilityid)
				throws ParseException {
			RespuestaMsgDto respuesta = new RespuestaMsgDto("");
			HttpStatus estatus = HttpStatus.FORBIDDEN;
			RoleDto detalleRoles;
			PrivilegesAllDto detallePrivilege;
			
			String var = "";
			boolean bloked = false;
			RespuestaDto respuestaDto = new RespuestaDto(var, bloked);
			String sessionid = request.getHeader("Authorization");
			Date fecha = new Date();
			SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			String dataFormattata = formatter.format(fecha);
			Date fechaDate = formatter.parse(dataFormattata);
			AuditRequestDto auditDto = new AuditRequestDto();
			RespuestaValueDto respuestaValueDto;
			String searchIn = "";


			Optional<Params> deSessDuration = paramsRepository.findByParamname("SESSION_DURATION");
			String SessionDuration = deSessDuration.get().getValue();
			int duracionSession = Integer.parseInt(SessionDuration);
			Date fecha2 = new Date();
			Calendar calendar = Calendar.getInstance();
			calendar.setTime(fecha2); // tuFechaBase es un Date;
			// calendar.add(Calendar.MINUTE, minutosASumar); //minutosASumar es int.
			calendar.add(Calendar.MINUTE, duracionSession); // horasASumar es int.
			// lo que más quieras sumar
			Date ValidThrufechaSalida = calendar.getTime(); // Y ya tienes la fecha sumada.

			if (sessionid == null) {
				respuesta.setMsg("Llamada al servicio malformado");
				estatus=HttpStatus.BAD_REQUEST;
				return new ResponseEntity(respuesta, estatus);
			} else {
				sessionid = sessionid.substring(7);
				Optional<Users> encontreSessionUsuario = usersRepository.getBySessionid(sessionid);

				if (encontreSessionUsuario.isPresent()) {
					//Eliminar un registro de un usuario. (priv 633)

					String fechaComoCadena;
					   Date FechaReg = encontreSessionUsuario.get().getValidthru(); 
						   //Llamada a la funcion que validad el tiempo de Session, retorna la fecha sumandole el tiempo de session activa, y vacio si no esta activa
						   
						   // fechaComoCadena  = securityService.consultarSessionActiva(FechaReg,fecha2);
						    fechaComoCadena  = securityService.consultarSessionActiva(FechaReg,fecha2,encontreSessionUsuario.get().getId());
						    if (fechaComoCadena=="") {
							   
							   
							   
							    String var2 = "";
								boolean bloked2 = false;
								RespuestaMsgDto respuestaDto2 = new RespuestaMsgDto(var2);
								//respuestaDto.setBlocked(bloked);
								respuestaDto2.setMsg("Sesión expirada o inválida"); 
								return new ResponseEntity(respuestaDto, HttpStatus.UNAUTHORIZED);
							   
						    }
						    
					  Roles roles = encontreSessionUsuario.get().getRolid();
					   int idrol = roles.getId();
					   int rolisvalid = auditRepository.getCantbyRolAndPrivi(idrol, 483);
					  // rolisvalid = 3;
					   if (rolisvalid==0) {
						  
						   
							//boolean bloked = false;
							RespuestaMsgDto respuestaPrivDto = new RespuestaMsgDto(var);
							//respuestaDto.setBlocked(bloked);
							respuestaPrivDto.setMsg("No tiene los Privilegios"); 
							return new ResponseEntity(respuestaPrivDto, HttpStatus.FORBIDDEN);
							
					   }
					   
					
					try {
						
						if (facilitiesRepository.existsById(facilityid)) {
							
							  Optional<Facilities> uniDelete = facilitiesRepository.findById(facilityid);
							   String module = "Instalaciones";
							     String Descmodule = "Se eliminó la Instalación: " + uniDelete.get().getName() + " con Id: " + uniDelete.get().getId();
							    
						         auditDto.setIpaddr(HttpReqRespUtils.getClientIpAddressIfServletRequestExist());
						       
						         String singo1 = "(";
						         String singo2 = ")";
						         String usryemail = encontreSessionUsuario.get().getUsr().concat(" ").concat(singo1).concat(encontreSessionUsuario.get().getEmail().concat(singo2));
						         auditDto.setUserref(usryemail);
						         auditDto.setModule(module);
						         auditDto.setDesc(Descmodule);
						         auditDto.setCreatedat(fechaDate);
						 		   usersService.registrarAuditSesion(auditDto); 
							
							// Borro el rol boolean existeUsers = ;
							int valor = 0;
							try {
							//usersRepository.deleteusersbyid(userid,fechaDate,valor);	
								facilitiesRepository.deleteFacilitiesid(facilityid);	
							    respuestaValueDto= new RespuestaValueDto(facilityid);
							
							
							estatus=HttpStatus.OK;
							return new ResponseEntity(respuestaValueDto, estatus);
							} catch (Exception e) {// Error Interno
								respuesta.setMsg("Error interno del servidor -conflicto. ");
								estatus=HttpStatus.CONFLICT;
								return new ResponseEntity(respuesta, estatus);
							} 
						} else {// Registro no encontrado
							respuesta.setMsg("Registro no encontrado");
							estatus=HttpStatus.NOT_FOUND;
							return new ResponseEntity(respuesta, estatus);
							
						}

					} catch (Exception e) {// Error Interno
						// Manejo de excepciones
						respuesta.setMsg("Error interno del servidor");
						estatus=HttpStatus.INTERNAL_SERVER_ERROR;
						return new ResponseEntity(respuesta, estatus);
					} finally {
						if (entityManager != null && entityManager.isOpen()) {
							entityManager.close();
						}
					}
				} else {
					respuesta.setMsg("Sesión expirada o inválida");
					estatus=HttpStatus.UNAUTHORIZED;
					return new ResponseEntity(respuesta, estatus);
					
				}

				
			}
			
		}
		
		
}
