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.ResponseBody;

import bean.AppVariables;
import bean.filters.DelegheSepaFilterBean;
import bean.filters.DisposizioniFiltroBean;
import bean.query.AggregatoAbiDelegaSepaQueryBean;
import bean.query.DelegaSepaQueryBean;
import bean.query.DisposizioniBonificiDecoded;
import common.controller.BaseController;
import dao.DelegheSepaDAO;
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.DisposizioniRid;
import sicura.entities.DistintaBanca;

@Controller
@RequestMapping("delegheSepa")
public class DelegaSepaRestController extends BaseController {

	@Autowired
	DelegheSepaDAO delegheSepaDAO;
	
	@RequestMapping(value="/list/{start:[\\d]+}-{length:[\\d]+}")
	@ResponseBody
	private ResponseEntity<Object> list(HttpServletRequest request, 
				@PathVariable("start") int startFrom, 
				@PathVariable("length") int length,
				@RequestBody DelegheSepaFilterBean delegheSepaFilterBean
				) {
		try {
			setRequest(request);
			AppVariables appVariables = (AppVariables) getSessionAttribute("appVariables");
			if(getUserData()==null)
				return new ResponseEntity<Object>(HttpStatus.UNAUTHORIZED);
			else
				if (delegheSepaFilterBean.isAggregazioneABI())
					return new ResponseEntity<Object>(delegheSepaDAO.listAggregatoAbi(startFrom,  length, delegheSepaFilterBean), HttpStatus.OK);
				else
					return new ResponseEntity<Object>(delegheSepaDAO.list(startFrom,length,delegheSepaFilterBean), HttpStatus.OK);
		} catch(Exception ex) {
			ex.printStackTrace();
			Logger.getRootLogger().error(ex);
			return new ResponseEntity<Object>(null, HttpStatus.INTERNAL_SERVER_ERROR);
		}

	}
	
	@RequestMapping(value="/count")
	@ResponseBody
	private ResponseEntity<Integer> count(HttpServletRequest request, @RequestBody DelegheSepaFilterBean delegheSepaFilterBean) {
		try {
			setRequest(request);
			AppVariables appVariables = (AppVariables) getSessionAttribute("appVariables");
			if(getUserData()==null)
				return new ResponseEntity<Integer>(HttpStatus.UNAUTHORIZED);
			else
				return new ResponseEntity<Integer>(delegheSepaDAO.count(delegheSepaFilterBean), HttpStatus.OK);
		} catch(Exception ex) {
			ex.printStackTrace();
			Logger.getRootLogger().error(ex);
			return new ResponseEntity(null, HttpStatus.INTERNAL_SERVER_ERROR);
		}
	}
	
	@RequestMapping(value="/print",method=RequestMethod.POST)
	private void print(@RequestBody DelegheSepaFilterBean delegheSepaFilterBean, HttpServletRequest request,HttpServletResponse response) throws Exception {
		setRequest(request);
		if(getUserData()==null)
			response.sendError(401); // UNAUTHORIZED
		else {
			AppVariables appVariables = (AppVariables) getSessionAttribute("appVariables");

			List<AggregatoAbiDelegaSepaQueryBean> deleghe = delegheSepaDAO.listAggregatoAbi(null,  null, delegheSepaFilterBean);
			if (deleghe.size()>0) {
				JRDataSource dsDisposizioni = new JRBeanCollectionDataSource(deleghe);
				
				HashMap<String, Object> reportParams = new HashMap<String, Object>();
				if ("0".equals(delegheSepaFilterBean.getTipo()))
					reportParams.put("rangeEstrazione", "Range Estrazione : Deleghe in carico");
				else if ("1".equals(delegheSepaFilterBean.getTipo()))
					reportParams.put("rangeEstrazione", "Range Estrazione : Deleghe non attive");
				else if ("2".equals(delegheSepaFilterBean.getTipo()))
					reportParams.put("rangeEstrazione", "Range Estrazione : Tutte le deleghe");
				
				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/repAggregazioneDelegheSeda.jasper" ,reportParams, dsDisposizioni);
				JasperExportManager.exportReportToPdfStream(jasperPrint, out);
				
				response.setContentType("application/pdf");
				response.setHeader("Content-Disposition","attachment;filename=AggregazioneDelegheSeda.pdf");
				
			    out.flush();
			    out.close();
			} else {
				response.setStatus(404); // not found
			}
		} 
	}
	
	@RequestMapping(value="/export")
	@ResponseBody
	private void export(@RequestBody DelegheSepaFilterBean delegheSepaFilterBean, HttpServletRequest request,HttpServletResponse response) throws Exception {
		setRequest(request);
		AppVariables appVariables = (AppVariables) getSessionAttribute("appVariables");
		if(getUserData()==null)
			response.sendError(401); // UNAUTHORIZED
		else {
			List<String> res= delegheSepaDAO.export(delegheSepaFilterBean);
			if (res.size()>1) {
				response.setContentType("text/csv");
				response.setHeader("Content-Disposition","attachment;filename=export.csv");
				ServletOutputStream out = response.getOutputStream();
				
				for (String str: res)
					out.println(str);
			    out.flush();
			    out.close();
			} else {
				response.setStatus(404); // not found
			}			    
		} 
		
	}

}
