package controller.rest;

import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;

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

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import bean.AppVariables;
import common.controller.BaseController;
import dao.RemunerationDao;
import net.sf.jasperreports.engine.JRDataSource;
import net.sf.jasperreports.engine.JRParameter;
import net.sf.jasperreports.engine.JasperExportManager;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.data.JRBeanCollectionDataSource;
import sicura.entities.RemunerationDetail;
import sicura.entities.RemunerationHeader;
import sicura.entities.RemunerationPrevisioning;

@Controller
@RequestMapping("remuneration")
public class RemunerationRestController extends BaseController{

	@Autowired
	RemunerationDao remunerationDao;
	
	@RequestMapping("/header/{start:[\\d]+}-{length:[\\d]+}")
	@ResponseBody
	private ResponseEntity<Object> listHeader(
			HttpServletRequest request,
			@PathVariable("start") int startFrom, 
			@PathVariable("length") int length,
			@RequestParam("codiceSia") String codiceSia) {
		try {
			setRequest(request);
			if(getUserData()==null)
				return new ResponseEntity<Object>(HttpStatus.UNAUTHORIZED);
			else {
				return new ResponseEntity<Object>(remunerationDao.getHeader(codiceSia,startFrom, length), HttpStatus.OK);
			}
		} catch(Exception ex) {
			ex.printStackTrace();
			Logger.getRootLogger().error(ex);
			return new ResponseEntity<>(null, HttpStatus.INTERNAL_SERVER_ERROR);
		}
	}

	@RequestMapping("/headercount")
	@ResponseBody
	private ResponseEntity<Integer> listHeader(@RequestParam("codiceSia") String codiceSia,HttpServletRequest request) {
		try {
			setRequest(request);
			if(getUserData()==null)
				return new ResponseEntity<Integer>(HttpStatus.UNAUTHORIZED);
			else {
				return new ResponseEntity<Integer>(remunerationDao.getHeaderCount(codiceSia), HttpStatus.OK);
			}
		} catch(Exception ex) {
			ex.printStackTrace();
			Logger.getRootLogger().error(ex);
			return new ResponseEntity<>(0, HttpStatus.INTERNAL_SERVER_ERROR);
		}
	}

	
	@RequestMapping("/provisioning/{idRemuneration}/{start:[\\d]+}-{length:[\\d]+}")
	@ResponseBody
	private ResponseEntity<Object> listProvisioning(
			HttpServletRequest request, 
			@PathVariable("idRemuneration") int idRemuneration,
			@PathVariable("start") int startFrom, 
			@PathVariable("length") int length) {
		try {
			setRequest(request);
			if(getUserData()==null)
				return new ResponseEntity<Object>(HttpStatus.UNAUTHORIZED);
			else {
				return new ResponseEntity<Object>(remunerationDao.getProvisioning(idRemuneration, startFrom, length), HttpStatus.OK);
			}
		} catch(Exception ex) {
			ex.printStackTrace();
			Logger.getRootLogger().error(ex);
			return new ResponseEntity<>(null, HttpStatus.INTERNAL_SERVER_ERROR);
		}
	}
	
	@RequestMapping("/provisioningcount/{idRemuneration}")
	@ResponseBody
	private ResponseEntity<Integer> countProvisioning(HttpServletRequest request, 
			@PathVariable("idRemuneration") int idRemuneration) {
		try {
			setRequest(request);
			if(getUserData()==null)
				return new ResponseEntity<Integer>(HttpStatus.UNAUTHORIZED);
			else {
				return new ResponseEntity<Integer>(remunerationDao.getProvisioningCount(idRemuneration), HttpStatus.OK);
			}
		} catch(Exception ex) {
			ex.printStackTrace();
			Logger.getRootLogger().error(ex);
			return new ResponseEntity<>(0, HttpStatus.INTERNAL_SERVER_ERROR);
		}
	}
	
	@RequestMapping("/detail/{idPrevisioning}/{start:[\\d]+}-{length:[\\d]+}")
	@ResponseBody
	private ResponseEntity<Object> listDetails(
			HttpServletRequest request, 
			@PathVariable("idPrevisioning") int idPrevisioning,
			@PathVariable("start") int startFrom, 
			@PathVariable("length") int length,
			@RequestParam(value="orderBy", required=false) String orderBy) {
		try {
			setRequest(request);
			if(getUserData()==null)
				return new ResponseEntity<Object>(HttpStatus.UNAUTHORIZED);
			else {
				return new ResponseEntity<Object>(remunerationDao.getDetails(idPrevisioning, startFrom, length, orderBy), HttpStatus.OK);
			}
		} catch(Exception ex) {
			ex.printStackTrace();
			Logger.getRootLogger().error(ex);
			return new ResponseEntity<>(null, HttpStatus.INTERNAL_SERVER_ERROR);
		}
	}
	
	@RequestMapping("/detailCount/{idRemuneration}")
	@ResponseBody
	private ResponseEntity<Integer> countDetails(HttpServletRequest request, 
			@PathVariable("idRemuneration") int idRemuneration) {
		try {
			setRequest(request);
			if(getUserData()==null)
				return new ResponseEntity<Integer>(HttpStatus.UNAUTHORIZED);
			else {
				return new ResponseEntity<Integer>(remunerationDao.getDetailsCount(idRemuneration), HttpStatus.OK);
			}
		} catch(Exception ex) {
			ex.printStackTrace();
			Logger.getRootLogger().error(ex);
			return new ResponseEntity<>(0, HttpStatus.INTERNAL_SERVER_ERROR);
		}
	}
	
	
	@RequestMapping("/generaRichiestaDettagli/{id}")
	@ResponseBody
	private  ResponseEntity<Object>generaRichiestaDettagli(
			@PathVariable("id") Integer id,
			@RequestParam("all") Boolean all,
			@RequestParam("tipoDettaglio") String tipoDettaglio,
			@RequestParam("tipoRichiesta") String tipoRichiesta,
			HttpServletRequest request) {
		try {
			setRequest(request);
			if(getUserData()==null)
				return new ResponseEntity<Object>(HttpStatus.UNAUTHORIZED);
			else {
				AppVariables appVariables = (AppVariables) getSessionAttribute("appVariables");
				String res = remunerationDao.generaRichiestaDettaglioMandati(appVariables,id, null,all, tipoDettaglio, tipoRichiesta);
				return new ResponseEntity<Object>(res, HttpStatus.OK);
			}
		} catch(Exception ex) {
			ex.printStackTrace();
			Logger.getRootLogger().error(ex);
			return new ResponseEntity<>(null, HttpStatus.INTERNAL_SERVER_ERROR);
		}
	}
	
	@RequestMapping("/generaRichiestaDettagli/{id}/{idDettaglio}")
	@ResponseBody
	private  ResponseEntity<Object>generaRichiestaDettagliTrimestre(
			@PathVariable("id") Integer id,
			@PathVariable("idDettaglio") Integer idDettaglio,
			@RequestParam("all") Boolean all,
			@RequestParam("tipoDettaglio") String tipoDettaglio,
			@RequestParam("tipoRichiesta") String tipoRichiesta,
			HttpServletRequest request) {
		try {
			setRequest(request);
			if(getUserData()==null)
				return new ResponseEntity<Object>(HttpStatus.UNAUTHORIZED);
			else {
				AppVariables appVariables = (AppVariables) getSessionAttribute("appVariables");
				String res = remunerationDao.generaRichiestaDettaglioMandati(appVariables,id, idDettaglio,all, tipoDettaglio, tipoRichiesta);
				return new ResponseEntity<Object>(res, HttpStatus.OK);
			}
		} catch(Exception ex) {
			ex.printStackTrace();
			Logger.getRootLogger().error(ex);
			return new ResponseEntity<>(null, HttpStatus.INTERNAL_SERVER_ERROR);
		}
		
	}

	@RequestMapping("/quadra/{id}")
	@ResponseBody
	private  ResponseEntity<Object>quadra(
			@PathVariable("id") Integer id,
			HttpServletRequest request) {
		try {
			setRequest(request);
			if(getUserData()==null)
				return new ResponseEntity<Object>(HttpStatus.UNAUTHORIZED);
			else {
				AppVariables appVariables = (AppVariables) getSessionAttribute("appVariables");
				String res = remunerationDao.quadra(appVariables,id, null);
				return new ResponseEntity<Object>(res, HttpStatus.OK);
			}
		} catch(Exception ex) {
			ex.printStackTrace();
			Logger.getRootLogger().error(ex);
			return new ResponseEntity<>(null, HttpStatus.INTERNAL_SERVER_ERROR);
		}
	}
	
	@RequestMapping("/exportMessaggi/{id}")
	private void exportMessaggi(@PathVariable("id") Integer id,HttpServletRequest request, HttpServletResponse response) throws Exception {
		setRequest(request);
		
		if(getUserData()==null)
			response.sendError(401); // UNAUTHORIZED
		else {
			AppVariables appVariables = (AppVariables) getSessionAttribute("appVariables");	
			List<String> file = remunerationDao.exportMessaggi(appVariables, id);
			if (file==null)
				return;
			response.setContentType("text/csv");
			response.setHeader("Content-Disposition",String.format("attachment;filename=messaggi.csv"));
			ServletOutputStream out = response.getOutputStream();
			for (String str: file)
				out.println(str);
		    out.flush();
		    out.close();
			
		}
		
	}
	
	@RequestMapping("/quadra/{id}/{idDettaglio}")
	@ResponseBody
	private  ResponseEntity<Object>quadraDettaglio(
			@PathVariable("id") Integer id,
			@PathVariable("idDettaglio") Integer idDettaglio,
			HttpServletRequest request) {
		try {
			setRequest(request);
			if(getUserData()==null)
				return new ResponseEntity<Object>(HttpStatus.UNAUTHORIZED);
			else {
				AppVariables appVariables = (AppVariables) getSessionAttribute("appVariables");
				String res = remunerationDao.quadra(appVariables,id, idDettaglio);
				return new ResponseEntity<Object>(res, HttpStatus.OK);
			}
		} catch(Exception ex) {
			ex.printStackTrace();
			Logger.getRootLogger().error(ex);
			return new ResponseEntity<>(null, HttpStatus.INTERNAL_SERVER_ERROR);
		}

	}
	
	@RequestMapping("/codiciSia")
	@ResponseBody
	private ResponseEntity<Object> getCodiciSia(HttpServletRequest request) {
		try {
			setRequest(request);
			if(getUserData()==null)
				return new ResponseEntity<Object>(HttpStatus.UNAUTHORIZED);
			else {
				return new ResponseEntity<Object>(remunerationDao.getCodiciSia(), HttpStatus.OK);
			}
		} catch(Exception ex) {
			ex.printStackTrace();
			Logger.getRootLogger().error(ex);
			return new ResponseEntity<>(null, HttpStatus.INTERNAL_SERVER_ERROR);
		}
	}
	
	@RequestMapping("/print/{idRemuneration}")
	@ResponseBody
	private void print(@PathVariable("idRemuneration") Integer idRemuneration, HttpServletRequest request,HttpServletResponse response) throws Exception {
		setRequest(request);
		if(getUserData()==null)
			response.sendError(401); // UNAUTHORIZED
		else {
			RemunerationHeader remuneration = remunerationDao.read(idRemuneration);
			List<RemunerationPrevisioning> previsioning = remunerationDao.getProvisioning(idRemuneration, 0, 0);
			if (previsioning.size()>0) {
				JRDataSource dsPrevisioning = new JRBeanCollectionDataSource(previsioning);
				
				SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy HH:mm");
				HashMap<String, Object> reportParams = new HashMap<String, Object>();
				String appPath = request.getSession().getServletContext().getRealPath("/");
				if (!appPath.endsWith("/"))
					appPath += "/";
				
				reportParams.put("dataRendiconto", sdf.format(remuneration.getDataRendi()));
				reportParams.put("codiceSIA", remuneration.getCodiceSia());
				reportParams.put("codiceABI", remuneration.getCodiceAbi());
				reportParams.put("banca", remuneration.getDenominazioneBanca());
				reportParams.put("checkimage", appPath+"img/checkbox.png");
				reportParams.put("uncheckimage", appPath+"img/uncheckbox.png");
				
				ServletOutputStream out = response.getOutputStream();
				
				java.util.Locale locale = new Locale( "it", "IT" );
				reportParams.put( JRParameter.REPORT_LOCALE, locale );
				
				JasperPrint jasperPrint = JasperFillManager.fillReport(appPath+"Reports/repRemunerazioneSedaTrimestre.jasper" ,reportParams, dsPrevisioning);
				JasperExportManager.exportReportToPdfStream(jasperPrint, out);
				
				response.setContentType("application/pdf");
				response.setHeader("Content-Disposition","attachment;filename=RemunerationSeda.pdf");
				
			    out.flush();
			    out.close();
			} else {
				response.setStatus(404); // not found
			}
		} 		
	}
	
	@RequestMapping("/printDetails/{idPrevisioning}")
	@ResponseBody
	private void printDetails(@PathVariable("idPrevisioning") Integer idPrevisioning, HttpServletRequest request,HttpServletResponse response) throws Exception {
		setRequest(request);
		if(getUserData()==null)
			response.sendError(401); // UNAUTHORIZED
		else {
			RemunerationPrevisioning previsioning = remunerationDao.getProvisioning(idPrevisioning);
			List<RemunerationDetail> details = remunerationDao.getDetails(previsioning.getIdprevisioning(), 0, 0, null);
			if (details.size()>0) {
				JRDataSource dsPrevisioning = new JRBeanCollectionDataSource(details);
				
				SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy HH:mm");
				HashMap<String, Object> reportParams = new HashMap<String, Object>();
				reportParams.put("trimestre", "Trimestre: " + previsioning.getTrimestre().toString());
				reportParams.put("anno", "Anno: " + previsioning.getAnno().toString());
				reportParams.put("idCreditore", "Identificativo Creditore: " + previsioning.getCreditorId());
				
				ServletOutputStream out = response.getOutputStream();
				
				String appPath = request.getSession().getServletContext().getRealPath("/");
				if (!appPath.endsWith("/"))
					appPath += "/";
				
				java.util.Locale locale = new Locale( "it", "IT" );
				reportParams.put( JRParameter.REPORT_LOCALE, locale );
				
				JasperPrint jasperPrint = JasperFillManager.fillReport(appPath+"Reports/repRemunerazioneSedaDetail.jasper" ,reportParams, dsPrevisioning);
				JasperExportManager.exportReportToPdfStream(jasperPrint, out);
				
				response.setContentType("application/pdf");
				response.setHeader("Content-Disposition","attachment;filename=RemunerationSeda.pdf");
				
			    out.flush();
			    out.close();
			} else {
				response.setStatus(404); // not found
			}		
		} 		
	}
	
}
