package com.bankaudit.template.rest.controller;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;

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.bind.annotation.RestController;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import com.bankaudit.constants.BankAuditConstant;
import com.bankaudit.service.BusinessDateService;
import com.bankaudit.template.rest.service.FileUploadReadTemplateService;
import com.bankaudit.template.rest.service.FileUploadWriteTemplateService;
import com.bankaudit.util.BankAuditUtil;
import com.bankaudit.util.ServiceStatus;





@RestController

@RequestMapping("/api/uploadTemplate")
public class TemplateController {

	@Autowired 
	FileUploadWriteTemplateService fileUploadWriteTemplateService;
	
	@Autowired 
	FileUploadReadTemplateService fileUploadReadTemplateService;
	
	@Autowired
	BusinessDateService businessDateService;
	
	ServiceStatus serviceStatus=null;

        
@RequestMapping(value="/getUploadTemplateType",method = RequestMethod.GET)
	    public void  getUploadTemplate(
	     		@RequestParam(value="tableName",required=true)String tableName,
	    		HttpServletRequest request,
	            HttpServletResponse response){
        	
        	try {	
        		if(tableName!=null && !BankAuditUtil.isEmptyString(tableName)) {
        			ServletOutputStream out = response.getOutputStream();
        			//String tableName = "maint_entity" ;

        			Date date = Calendar.getInstance().getTime();
        			DateFormat formatter = new SimpleDateFormat("ddMMyyyy");
        			String today = formatter.format(date);

        			response.setHeader("Content-Disposition","attachment; filename=\"" + tableName + today + ".xls\"");
        			response.setContentType("application/vnd.ms-excel;charset=ISO-8859-1");	    	
        			HSSFWorkbook workBook = fileUploadWriteTemplateService.writeTemplate(tableName);
        			workBook.write(out);
        		}else {
        			throw new Exception("invalid input ");
        		}
        	} catch (Exception e) {
    			e.printStackTrace();    			
    		}
	    }
	
       
@RequestMapping(value="/getUploadTemplateLov",method = RequestMethod.GET)
        ServiceStatus getUploadType(){
    	   serviceStatus = new ServiceStatus();
        	try {
        		serviceStatus.setResult(fileUploadWriteTemplateService.getUploadType());
				serviceStatus.setStatus("success");
				serviceStatus.setMessage("successfuly retrieved ");
				
        	} catch (Exception e) {
    			serviceStatus.setStatus("failure");
    			serviceStatus.setMessage("failure");
    			e.printStackTrace();
    		}
			return serviceStatus;
        }
       
       
        
        
@RequestMapping(value="/loadUploadTemplate" ,method=RequestMethod.POST,consumes=MediaType.MULTIPART_FORM_DATA_VALUE,produces=MediaType.APPLICATION_JSON_VALUE)
    	ServiceStatus uploadTemplate(
    			@RequestParam(value="maker", required=false)String maker,
    			@RequestParam(value="role", required=false)String role,
    			@RequestParam(value="tableName", required=false)String tableName,
    			@RequestParam(value="files", required=false)CommonsMultipartFile[] files,
    			@RequestParam(value="legalEntityCode", required=false)Integer legalEntityCode) {
        	serviceStatus = new ServiceStatus();
        	String message="";
        	try {
        		if (files==null) {
        			message=" No file is attached to upload.";
        		}else if(maker==null || "".equals(maker)){
        			message=" In valied Maker.";
        		}else if(role==null || "".equals(role)) {
        			message=" In valied Role.";
        		}else if(tableName==null || "".equals(tableName)) {
        			message=" In valied Template name.Please select template from Lov to uploaded.";
        		}else if(legalEntityCode==null || legalEntityCode<0) {
        			message=" In valied LegalEntity.";
        		}else {			
        			for ( CommonsMultipartFile commonsMultipartFile : files) {
        				if(commonsMultipartFile.getContentType()!=null && !BankAuditUtil.validateFileType(commonsMultipartFile, BankAuditConstant.DOC_TYPES) && 
        						!"xls".equals(BankAuditUtil.getFileExtension(commonsMultipartFile.getOriginalFilename()))){
        					message="file type : "+BankAuditUtil.getFileExtension(commonsMultipartFile.getOriginalFilename())+" not supported, Please upload xls files only.";
        				}else if ("".equals(message)  ) {
        					Date businessDate=businessDateService.getBusinessDateTimestampByLegalEntityCode(legalEntityCode);
        					message=fileUploadReadTemplateService.readTemplate(commonsMultipartFile,tableName,maker,businessDate);
        				}
        			}
        		}
        		if(!"".equals(message)) {
        			serviceStatus.setStatus("failure");
        			serviceStatus.setMessage(message);
        		}else {
        			serviceStatus.setStatus("success");
        			serviceStatus.setMessage("successsfully uploaded...");
        		}
        	}catch (Exception e) {
        		e.printStackTrace();
        		serviceStatus.setStatus("failure");
        		serviceStatus.setMessage(e.getMessage());
        	}
        	return serviceStatus;
        }
}
