package controller.rest;

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.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import bean.AppVariables;
import bean.CambioOrdinanteBean;
import bean.query.DestinatarioForPrinting;
import common.controller.BaseController;
import dao.DestinatariDao;
import dao.OrdinantiDao;
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.Destinatari;
import sicura.entities.Ordinanti;

@Controller
@RequestMapping("destinatari")
public class DestinatariRestController extends BaseController {

	@Autowired
	DestinatariDao destinatariDao;
		
	@RequestMapping(value="/list/{idOrdinante}/{start:[\\d]+}-{length:[\\d]+}")
	@ResponseBody
	private ResponseEntity<List<Destinatari>> list(@PathVariable("idOrdinante") Integer idOrdinante, HttpServletRequest request,
			@PathVariable("start") int startFrom, 
			@PathVariable("length") int length,
			@RequestParam(value="filter",required=false) String filter,
			@RequestParam(value="orderBy",required=false) String orderField) {
		try {
			setRequest(request);
			if(getUserData()==null)
				return new ResponseEntity<List<Destinatari>>(HttpStatus.UNAUTHORIZED);
			else
				return new ResponseEntity<List<Destinatari>>(destinatariDao.listForOrdinante(idOrdinante, startFrom, length, filter, orderField), HttpStatus.OK);
		} catch(Exception ex) {
			ex.printStackTrace();
			Logger.getRootLogger().error(ex);
			return new ResponseEntity(null, HttpStatus.INTERNAL_SERVER_ERROR);
		}
	}
	
	@RequestMapping(value="/count/{idOrdinante}")
	@ResponseBody
	private ResponseEntity<Integer> count(@PathVariable("idOrdinante") Integer idOrdinante, 
				@RequestParam(value="filter",required=false) String filter,
				HttpServletRequest request) {
		try {
			setRequest(request);
			if(getUserData()==null)
				return new ResponseEntity<Integer>(HttpStatus.UNAUTHORIZED);
			else
				return new ResponseEntity<Integer>(destinatariDao.countForOrdinante(idOrdinante, filter), HttpStatus.OK);
		} catch(Exception ex) {
			ex.printStackTrace();
			Logger.getRootLogger().error(ex);
			return new ResponseEntity<>(null, HttpStatus.INTERNAL_SERVER_ERROR);
		}
	}	
	
	
	@RequestMapping(value="", method=RequestMethod.POST)
	@ResponseBody
	private ResponseEntity<Object> count(@RequestBody Destinatari destinatario, HttpServletRequest request) {
		try {
			setRequest(request);
			if(getUserData()==null)
				return new ResponseEntity<Object>(HttpStatus.UNAUTHORIZED);
			else {
				try {
					AppVariables appVariables = (AppVariables) getSessionAttribute("appVariables");
					return new ResponseEntity<Object>(destinatariDao.save(destinatario, appVariables), HttpStatus.OK);
				} catch (Exception ex) {
					return new ResponseEntity<Object>(ex.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR);
				}
			}
		} catch(Exception ex) {
			ex.printStackTrace();
			Logger.getRootLogger().error(ex);
			return new ResponseEntity<Object>(null, HttpStatus.INTERNAL_SERVER_ERROR);
		}
	}	
	
	@RequestMapping(value="/new", method=RequestMethod.GET)
	@ResponseBody
	private ResponseEntity<Object> newInstance(HttpServletRequest request) {
		try {
			setRequest(request);
			if(getUserData()==null)
				return new ResponseEntity<Object>(HttpStatus.UNAUTHORIZED);
			else {
				try {
					Destinatari destinatario = new Destinatari();
					destinatario.setIddestinatario(0);
					return new ResponseEntity<Object>(destinatario, HttpStatus.OK);
				} catch (Exception ex) {
					return new ResponseEntity<Object>(ex.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR);
				}
			}
		} catch(Exception ex) {
			ex.printStackTrace();
			Logger.getRootLogger().error(ex);
			return new ResponseEntity<Object>(null, HttpStatus.INTERNAL_SERVER_ERROR);
		}
	}	
	
	@RequestMapping(value="/{idDestinatario}", method=RequestMethod.DELETE)
	@ResponseBody
	private ResponseEntity<Object> deleteDestinatario(@PathVariable("idDestinatario") Integer idDestinatario, HttpServletRequest request) {
		try {
			setRequest(request);
			if(getUserData()==null)
				return new ResponseEntity<Object>(HttpStatus.UNAUTHORIZED);
			else  {
				AppVariables appVariables = (AppVariables) getSessionAttribute("appVariables");
				try {
					destinatariDao.delete(idDestinatario, appVariables);
					return new ResponseEntity<Object>(HttpStatus.OK);
				} catch (Exception ex) {
					return new ResponseEntity<Object>(ex.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR);
				}
			}
		} catch(Exception ex) {
			ex.printStackTrace();
			Logger.getRootLogger().error(ex);
			return new ResponseEntity<Object>(null, HttpStatus.INTERNAL_SERVER_ERROR);
		}
	}	
	
	@RequestMapping(value="/cambioOrdinante", method=RequestMethod.POST)
	@ResponseBody
	private ResponseEntity<Object> cambioOrdinante(@RequestBody CambioOrdinanteBean cambioOrdinanteBean, HttpServletRequest request) {
		try {
			setRequest(request);
			if(getUserData()==null)
				return new ResponseEntity<Object>(HttpStatus.UNAUTHORIZED);
			else  {
				AppVariables appVariables = (AppVariables) getSessionAttribute("appVariables");
				destinatariDao.cambioOrdinante(cambioOrdinanteBean, appVariables);
				return new ResponseEntity<Object>(HttpStatus.OK);
			}
		} catch(Exception ex) {
			ex.printStackTrace();
			Logger.getRootLogger().error(ex);
			return new ResponseEntity<Object>(null, HttpStatus.INTERNAL_SERVER_ERROR);
		}
	}
	
	@RequestMapping(value="/print/{idOrdinante}",method=RequestMethod.GET)
	private void print(@PathVariable("idOrdinante") Integer idOrdinante, HttpServletRequest request,HttpServletResponse response) throws Exception {
		setRequest(request);
		if(getUserData()==null)
			response.sendError(401); // UNAUTHORIZED
		else {
			AppVariables appVariables = (AppVariables) getSessionAttribute("appVariables");
			List<DestinatarioForPrinting> destinatari = destinatariDao.listForPrinting(idOrdinante);
			if (destinatari.size()>0) {
				JRDataSource dsDestinatari= new JRBeanCollectionDataSource(destinatari);
				
				HashMap reportParams = new HashMap();
				
				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/repDestinatari.jasper" ,reportParams, dsDestinatari);
				JasperExportManager.exportReportToPdfStream(jasperPrint, out);
				
				response.setContentType("application/pdf");
				response.setHeader("Content-Disposition","attachment;filename=Destinatari.pdf");
				
			    out.flush();
			    out.close();
			} else {
				response.setStatus(404); // not found
			}
		} 
	}
}
