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

import bean.AppVariables;
import bean.LogModificheBean;
import bean.query.DistintaBancaBean;
import common.controller.BaseController;
import dao.DistintaFlussiInputDAO;
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.DistintaFlussiInput;

@Controller
@RequestMapping("DistintaFlussiInput")
public class DistintaFlussiInputRestController extends BaseController {
	
	@Autowired 
	DistintaFlussiInputDAO distintaFlussiInputDao;
	
	@RequestMapping("/count")
	@ResponseBody
	private ResponseEntity<Integer> count(HttpServletRequest request) {
		try {
			setRequest(request);
			if(getUserData()==null)
				return new ResponseEntity<Integer>(HttpStatus.UNAUTHORIZED);
			else {
				AppVariables appVariables =  (AppVariables) getSessionAttribute("appVariables");
				return new ResponseEntity<Integer>(distintaFlussiInputDao.getFlussiCount(appVariables), HttpStatus.OK);
			}
		} catch(Exception ex) {
			ex.printStackTrace();
			Logger.getRootLogger().error(ex);
			return new ResponseEntity<>(0, HttpStatus.INTERNAL_SERVER_ERROR);
		}					
	}
	
	@RequestMapping(value="/list/{start:[\\d]+}-{length:[\\d]+}")
	@ResponseBody
	private ResponseEntity<Object> list(HttpServletRequest request, 
				@PathVariable("start") int startFrom, 
				@PathVariable("length") int length,
				@RequestParam(value="orderBy", required=false) String orderField	
				) {
		try {
			setRequest(request);
			if(getUserData()==null)
				return new ResponseEntity<Object>(HttpStatus.UNAUTHORIZED);
			else {
				AppVariables appVariables = (AppVariables) getSessionAttribute("appVariables");
				return new ResponseEntity<Object>(distintaFlussiInputDao.getFlussi(appVariables,startFrom,length,orderField), HttpStatus.OK);
			}
		} catch(Exception ex) {
			ex.printStackTrace();
			Logger.getRootLogger().error(ex);
			return new ResponseEntity<>(null, HttpStatus.INTERNAL_SERVER_ERROR);
		}
	}
	
	@RequestMapping("/annulla/{id}")
	@ResponseBody
	private ResponseEntity<String> annullaFlusso(
				@PathVariable("id") Integer id,
				HttpServletRequest request) {
		try{
			setRequest(request);
			if(getUserData()==null)
				return new ResponseEntity<String>(HttpStatus.UNAUTHORIZED);
			else {
				AppVariables appVariables = (AppVariables) getSessionAttribute("appVariables");
				return new ResponseEntity<String>(distintaFlussiInputDao.annullaFlusso(id,appVariables), HttpStatus.OK);
			}
		} catch(Exception ex) {
			ex.printStackTrace();
			Logger.getRootLogger().error(ex);
			return new ResponseEntity<>(null, HttpStatus.INTERNAL_SERVER_ERROR);
		}
			
	}
	
	@RequestMapping(value="/logStati/{id}")
	@ResponseBody
	private ResponseEntity<List<LogModificheBean>> logStati(HttpServletRequest request, @PathVariable("id") Integer id) {
		try {
			setRequest(request);
			AppVariables appVariables = (AppVariables) getSessionAttribute("appVariables");
			if(getUserData()==null)
				return new ResponseEntity<List<LogModificheBean>>(HttpStatus.UNAUTHORIZED);
			else
				return new ResponseEntity<List<LogModificheBean>>(distintaFlussiInputDao.logStati(id), HttpStatus.OK);
		} catch(Exception ex) {
			ex.printStackTrace();
			Logger.getRootLogger().error(ex);
			return new ResponseEntity<>(null, HttpStatus.INTERNAL_SERVER_ERROR);
		}
	}
	
	@RequestMapping(value="/print")
	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<DistintaFlussiInput> distinte = distintaFlussiInputDao.getFlussi(appVariables, null, null, null);
			if (distinte.size()>0) {
				JRDataSource dsDistinte = new JRBeanCollectionDataSource(distinte);
				
				HashMap<String, Object> reportParams = new HashMap<String, Object>();
				String appPath = request.getSession().getServletContext().getRealPath("/");
				if (!appPath.endsWith("/"))
					appPath += "/";
				
				reportParams.put("checked", appPath+"img/checkbox.png");
				reportParams.put("unchecked", 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/repLogFlussiInput.jasper" ,reportParams, dsDistinte);
				JasperExportManager.exportReportToPdfStream(jasperPrint, out);
				
				response.setContentType("application/pdf");
				response.setHeader("Content-Disposition","attachment;filename=LogFlussiInput.pdf");
				
			    out.flush();
			    out.close();
			} else {
				response.setStatus(404); // not found
			}			    
		}
	}

}
