/*******************************************************************************
 * Copyright 2014 2Fi Business Solutions Ltd.
 *
 * This code is part of the PCS project.
 *
 * 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.order.web;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.text.DateFormat;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.mail.internet.InternetAddress;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.jboss.jandex.UnsupportedVersion;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.ServletRequestBindingException;
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.JRException;
import net.sf.jasperreports.engine.data.JRBeanCollectionDataSource;

import com.ffii.core.utils.MapUtils;
import com.ffii.core.utils.Params;
import com.ffii.core.utils.SecurityUtils;
import com.ffii.core.web.AbstractController;
import com.ffii.core.web.view.json.JsonView;
import com.ffii.tbms.customer.service.CustomerService;
import com.ffii.tbms.file.FileBlob;
import com.ffii.tbms.mail.service.MailService;
import com.ffii.tbms.order.service.InvoiceService;
import com.ffii.tbms.order.service.OrderService;
import com.ffii.tbms.user.service.SysGroupService;
import com.ffii.tbms.user.service.UserService;


@Controller
@RequestMapping(value = "/order/invoice")
public class InvoiceController extends AbstractController {
	@Autowired
	private InvoiceService invoiceService;

	@Autowired
	private MailService mailService;

	@Autowired
	private SysGroupService sysGroupService;


	
	@RequestMapping(value = "/send", method = { RequestMethod.GET, RequestMethod.POST })
	public String sendInvoice(Model model, HttpServletRequest request, @RequestParam int orderId,
	 @RequestParam String subject, @RequestParam String body)
	 throws ServletRequestBindingException, IllegalStateException, IOException, JRException {

		Map<String, Object> order = invoiceService.search(orderId);
				
		if (order.get("email") == null || order.get("email").toString().isEmpty()) {
			model.addAttribute(Params.SUCCESS, Boolean.FALSE);
			model.addAttribute(Params.MSG, "Email Invalid.");
			return JsonView.NAME;
		}
	
		InternetAddress recipient = null;
		try {
			recipient = new InternetAddress(order.get("Email").toString(),"");
			//recipient = new InternetAddress("hmiufong@gmail.com", "");
		} catch (UnsupportedVersion e) {
			// omg wtf cannot create InternetAddress
			e.printStackTrace();
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		if (recipient != null) {
			
				mailService.sendSystemMail(
				SecurityUtils.getUser().getSysGroupId(),
				mailService.getFromAddress(SecurityUtils.getUser().getSysGroupId()),
				MailService.FIX_RECIPIENT,
				recipient,
				subject,
				"mail/contentMail.ftl",
				MapUtils.toHashMap("content",body),
				"invoice.pdf",
				new ByteArrayResource(invoiceService.genInvoice(orderId)));
						
			model.addAttribute(Params.SUCCESS, Boolean.TRUE);
		} else {
			model.addAttribute(Params.SUCCESS, Boolean.FALSE);
		}

		model.addAttribute(Params.AUTH, Boolean.TRUE);
		model.addAttribute(Params.SUCCESS, Boolean.TRUE);

		return JsonView.NAME;
	}


	@RequestMapping(value = "/get-cust-contact", method = { RequestMethod.GET, RequestMethod.POST })
	public String getCustContact(Model model, HttpServletRequest request, @RequestParam int orderId) throws ServletRequestBindingException, IllegalStateException, IOException, JRException {

		SimpleDateFormat df = new SimpleDateFormat("dd MMMM yyyy");
		DecimalFormat decimalFormat = new DecimalFormat("#,##0.00");

		Map<String, Object> data = invoiceService.search(orderId);
		BigDecimal amount = (BigDecimal)invoiceService.getOrderItemTotalAmount(orderId).get("totalAmount");
		amount = amount == null? BigDecimal.ZERO: amount;
		String subject = invoiceService.getTemplateSubject();
		subject = subject.replaceAll("\\{\\$orderNo\\}",data.get("orderNo").toString());
		subject = subject.replaceAll("\\{\\$orderDate\\}",df.format(data.get("orderDate")));
		subject = subject.replaceAll("\\{\\$amount\\}","\\$ "+decimalFormat.format(amount));
		subject = subject.replaceAll("\\{\\$today\\}",df.format(new Date()));
		subject = subject.replaceAll("\\{\\$nameCh\\}",data.get("nameCh")==null?"":data.get("nameCh").toString());
		subject = subject.replaceAll("\\{\\$firstName\\}",data.get("firstName")==null?"":data.get("firstName").toString());
		subject = subject.replaceAll("\\{\\$surname\\}",data.get("surname")==null?"":data.get("surname").toString());
		data.put("subject", subject);
		String body = invoiceService.getTemplateBody();
		body = body.replaceAll("\\{\\$orderNo\\}",data.get("orderNo").toString());
		body = body.replaceAll("\\{\\$orderDate\\}",df.format(data.get("orderDate")));
		body = body.replaceAll("\\{\\$amount\\}","\\$ "+decimalFormat.format(amount));
		body = body.replaceAll("\\{\\$today\\}",df.format(new Date()));
		body = body.replaceAll("\\{\\$nameCh\\}",data.get("nameCh")==null?"":data.get("nameCh").toString());
		body = body.replaceAll("\\{\\$firstName\\}",data.get("firstName")==null?"":data.get("firstName").toString());
		body = body.replaceAll("\\{\\$surname\\}",data.get("surname")==null?"":data.get("surname").toString());
		data.put("body", body);

		model.addAttribute(Params.DATA, data);
		model.addAttribute(Params.AUTH, Boolean.TRUE);
		model.addAttribute(Params.SUCCESS, Boolean.TRUE);

		return JsonView.NAME;
	}

	
	@RequestMapping(value = "/invoice.pdf", method = { RequestMethod.GET,RequestMethod.POST })
	public ModelAndView invoicePdf(Model model, HttpServletRequest request, HttpServletResponse response,
			@RequestParam int orderId) throws Exception {
			
			Map<String, Object> params = invoiceService.getInvoicePdfParams(orderId);

			List<Map<String,Object>> list = invoiceService.getOrderItems(orderId);

			if(list == null || list.size()==0){
				for(int i =0; i<12; i++)
					list.add(new HashMap<String, Object>());
			}else{
				int line = 12-list.size();
				for(int i = 0; i<line; i++)
					list.add(new HashMap<String, Object>());
			}

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

			
			ScriptEngineManager manager = new ScriptEngineManager();
			ScriptEngine engine = manager.getEngineByName("js");
			Object result = engine.eval("4.0*5");

			return new ModelAndView("invoiceTemp", params);
	}


}
