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.filters.DisposizioniFiltroBean;
import bean.query.DisposizioniAeaDecoded;
import common.controller.BaseController;
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.DistintaBanca;
import sicura.entities.Ordinanti;

@Controller
@RequestMapping("ordinanti")
public class OrdinantiRestController extends BaseController {

	@Autowired
	OrdinantiDao ordinantiDao;
		
	@RequestMapping(value="/list")
	@ResponseBody
	private ResponseEntity<List<Ordinanti>> list(@RequestParam(value="filter",required=false) String filter, HttpServletRequest request) {
		try {
			setRequest(request);
			AppVariables appVariables = (AppVariables) getSessionAttribute("appVariables");
			if(getUserData()==null)
				return new ResponseEntity<List<Ordinanti>>(HttpStatus.UNAUTHORIZED);
			else
				return new ResponseEntity<List<Ordinanti>>(ordinantiDao.list(0,9999,filter,null), HttpStatus.OK);
		} catch(Exception ex) {
			ex.printStackTrace();
			Logger.getRootLogger().error(ex);
			return new ResponseEntity<>(null, HttpStatus.INTERNAL_SERVER_ERROR);
		}
	}
	
	
	@RequestMapping(value="/count")
	@ResponseBody
	private ResponseEntity<Integer> count(@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>(ordinantiDao.count(filter), HttpStatus.OK);
		} catch(Exception ex) {
			ex.printStackTrace();
			Logger.getRootLogger().error(ex);
			return new ResponseEntity<>(0, HttpStatus.INTERNAL_SERVER_ERROR);
		}
	}
	
	@RequestMapping(value="", method=RequestMethod.POST)
	@ResponseBody
	private ResponseEntity<Object> save(@RequestBody Ordinanti ordinante, 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>(ordinantiDao.save(ordinante, 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<>("Si è verificato un errore imprevisto.  L'errore è stato registrato nel log di Sicura", HttpStatus.INTERNAL_SERVER_ERROR);
		}
		
	}
	
	@RequestMapping(value="/new")
	@ResponseBody
	private ResponseEntity<Ordinanti> newInstance(HttpServletRequest request) {
		try {
			setRequest(request);
			if(getUserData()==null)
				return new ResponseEntity<Ordinanti>(HttpStatus.UNAUTHORIZED);
			else {
				Ordinanti ordinante = new Ordinanti();
				ordinante.setIdordinante(0);
				return new ResponseEntity<Ordinanti>(ordinante, HttpStatus.OK);
			}
		} catch(Exception ex) {
			ex.printStackTrace();
			Logger.getRootLogger().error(ex);
			return new ResponseEntity<>(null, HttpStatus.INTERNAL_SERVER_ERROR);
		}
	}
	
	@RequestMapping(value="/{idordinante}")
	@ResponseBody
	private ResponseEntity<Object> delete(@PathVariable("idordinante") Integer idOrdinante, HttpServletRequest request) {
		try {
			setRequest(request);
			if(getUserData()==null)
				return new ResponseEntity<Object>(HttpStatus.UNAUTHORIZED);
			else {
				AppVariables appVariables = (AppVariables) getSessionAttribute("appVariables");
				try {
					return new ResponseEntity<Object>(ordinantiDao.delete(idOrdinante, appVariables), HttpStatus.OK);
				} catch (Exception e) {
					e.printStackTrace();
					return new ResponseEntity<Object>(e.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR);
				}
			}
		} catch(Exception ex) {
			ex.printStackTrace();
			Logger.getRootLogger().error(ex);
			return new ResponseEntity<>(null, HttpStatus.INTERNAL_SERVER_ERROR);
		}
	}
	
	@RequestMapping(value="/print",method=RequestMethod.GET)
	private void print(HttpServletRequest request,HttpServletResponse response) throws Exception {
		setRequest(request);
		if(getUserData()==null)
			response.sendError(401); // UNAUTHORIZED
		else {
			AppVariables appVariables = (AppVariables) getSessionAttribute("appVariables");
			List<Ordinanti> ordinanti = ordinantiDao.list(0,9999,null,null);
			if (ordinanti.size()>0) {
				JRDataSource dsOrdinanti = new JRBeanCollectionDataSource(ordinanti);
				
				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/repOrdinanti.jasper" ,reportParams, dsOrdinanti);
				JasperExportManager.exportReportToPdfStream(jasperPrint, out);
				
				response.setContentType("application/pdf");
				response.setHeader("Content-Disposition","attachment;filename=Ordinanti.pdf");
				
			    out.flush();
			    out.close();
			} else {
				response.setStatus(404); // not found
			}
		} 
	}
}
