/*******************************************************************************
 * 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.BufferedImage;
import java.io.File;

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

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.utils.ZXingUtils;
import com.ffii.core.web.AbstractController;
import com.ffii.tbms.order.service.OrderService;

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

	@Autowired
	private OrderService orderService;

	@RequestMapping(value = "/measurement-sheet.{format}", method = { RequestMethod.GET,RequestMethod.POST })
	public ModelAndView measurementSheet(Model model, HttpServletRequest request, HttpServletResponse response,
			@RequestParam int orderId,
			@PathVariable String format) throws Exception {
			
			List<Map<String,Object>> list = new ArrayList<>();
			Map<String, Object> params = new HashMap<>();

			Map<String, Object> data = orderService.find(MapUtils.toHashMap("orderId", orderId));

			String path = this.getClass().getClassLoader().getResource("").getPath() + "../report/measurementSheetImage.jpeg";
			BufferedImage msImage = ImageIO.read(new File(path));
			list.add(MapUtils.toHashMap("msImage", msImage,
										"codeImage", ZXingUtils.encodeToImageCode128("0"+data.get("id").toString(), 160, 50),
										"custName", data.get("customerName"),
										"orderNo", data.get("orderNo")));
			params.put("dataSource", new JRBeanCollectionDataSource(list));

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