/*******************************************************************************
 * Copyright 2019 2Fi Business Solutions Ltd.
 *
 *
 *
 * This code is copyrighted. Under no circumstances should any party, people,
 * or organization should redistribute any portions of this code in any form,
 * either verbatim or through electronic media, to any third parties, unless
 * under explicit written permission by 2Fi Business Solutions Ltd.
 ******************************************************************************/
package com.ffii.tbms.reports.web;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.imgscalr.Scalr;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
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.servlet.ModelAndView;

import net.sf.jasperreports.engine.data.JRBeanCollectionDataSource;
import com.ffii.core.utils.MapUtils;
import com.ffii.core.web.AbstractController;
import com.ffii.tbms.file.FileBlob;
import com.ffii.tbms.file.service.FileService;

@Controller
@RequestMapping(value = "/report")
public class PreviewController extends AbstractController {

	@Autowired
	private FileService fileService;

	@RequestMapping(value = "preview.{format}", method = { RequestMethod.GET,RequestMethod.POST })
	public ModelAndView printJobSheet(Model model, HttpServletRequest request, HttpServletResponse response,
			@RequestParam int[] fileIds,
			@PathVariable String format) throws Exception {

			List<Map<String,Image>> selectedList = new ArrayList<>();

			Map<String, Object> params = new HashMap<>();

			for(int fileId: fileIds){
				FileBlob fileBlob = fileService.findFileBlobByFileId(fileId);
				BufferedImage image = ImageIO.read(new ByteArrayInputStream(fileBlob.getBytes()));
				if(image.getWidth()>image.getHeight()){
					BufferedImage rotated = Scalr.rotate(image, Scalr.Rotation.CW_270, Scalr.OP_ANTIALIAS);
					image = Scalr.resize(rotated, Scalr.Method.SPEED, Scalr.Mode.FIT_TO_HEIGHT,
					 image.getHeight(), image.getWidth(), Scalr.OP_ANTIALIAS);
				}
				selectedList.add(MapUtils.toHashMap("selectedImage", image));
			}

			params.put("dataSource", new JRBeanCollectionDataSource(selectedList));

			if (format.equals("pdf") || format.equals("docx"))
				params.put("format", format);
			else
				params.put("format", "pdf");
						
			return new ModelAndView("tbmsPrintPreview", params);
	}
}
