package com.reallinkbilling.download;

import static java.awt.Color.WHITE;
import static org.apache.pdfbox.pdmodel.font.PDType1Font.HELVETICA;
import static org.vandeseer.easytable.settings.HorizontalAlignment.CENTER;
import static org.vandeseer.easytable.settings.HorizontalAlignment.LEFT;
import static org.vandeseer.easytable.settings.HorizontalAlignment.RIGHT;

import java.awt.Color;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.PrintWriter;
import java.sql.Blob;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.fontbox.ttf.TTFParser;
import org.apache.fontbox.ttf.TrueTypeFont;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;
import org.apache.pdfbox.pdmodel.PDPageContentStream;
import org.apache.pdfbox.pdmodel.common.PDRectangle;
import org.apache.pdfbox.pdmodel.font.PDFont;
import org.apache.pdfbox.pdmodel.font.PDType0Font;
import org.apache.pdfbox.pdmodel.font.PDType1Font;
import org.apache.pdfbox.pdmodel.graphics.image.PDImageXObject;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.dispatcher.SessionMap;
import org.apache.struts2.interceptor.SessionAware;
import org.vandeseer.easytable.TableDrawer;
import org.vandeseer.easytable.structure.Row;
import org.vandeseer.easytable.structure.Table;
import org.vandeseer.easytable.structure.Table.TableBuilder;
import org.vandeseer.easytable.structure.cell.TextCell;

import com.opensymphony.xwork2.ActionSupport;
import com.reallinkbilling.DAO.BillProductInfoDAO;

public class PrintCalculatorBill extends ActionSupport implements SessionAware{
	
	
	
	/**
	 * 
	 */
	private static final long serialVersionUID = -287465310319606813L;
	public HttpServletRequest request;
	public HttpServletResponse response;

	private final static Color BLUE_DARK = new Color(76, 129, 190);
    private final static Color BLUE_LIGHT_1 = new Color(186, 206, 230);
    private final static Color BLUE_LIGHT_2 = new Color(218, 230, 242);

    private final static Color GRAY_LIGHT_1 = new Color(245, 245, 245);
    private final static Color GRAY_LIGHT_2 = new Color(240, 240, 240);
    private final static Color GRAY_LIGHT_3 = new Color(216, 216, 216);
    private static final float PADDING10 = 10f;
    private static final float PADDING20 = 20f;
    private static final float PADDING30 = 30f;
    private static final float PADDING40 = 40f;
    private static final float PADDING50 = 50f;
    
	
	private SessionMap<String,Object> sessionMap;  
	private ArrayList<Float> figureList = new ArrayList<Float>();
	
	public void printCalculatorBill()
	{
		
		 
        if(this.getSessionMap()==null || this.getSessionMap().get("login")==null){ 
        	addActionMessage("Please Login First !!!");
        	
        }  
        else{
        	
        	String shopId = (String) this.getSessionMap().get("shopId");
    		String shopCode = (String) this.getSessionMap().get("shopCode");

    		String fullUserName = (String) this.getSessionMap().get("userFullName");
        	
        	String splitUserName [] = new String[5];
        	
        	String billedBy = "";
        	try
        	{
        		splitUserName = fullUserName.split(" ");
        		billedBy = splitUserName[0];
        		
        	}catch(Exception e)
        	{
        		billedBy =fullUserName;
        	}
        	
        	HashMap<String,String> shopSettingsMap = (HashMap<String, String>) this.getSessionMap().get("shop_settings");
			
			
			String addDiscountColumnString = shopSettingsMap.get("add_discount_column_to_bill");
			String addQRCodeString = shopSettingsMap.get("add_QR_code_to_bill");
			String addGSTNumberString = shopSettingsMap.get("add_gst_number_to_bill");
			String addCustCreditAmtSettings = shopSettingsMap.get("add_credit_amount_to_bill");
			String billMessageFont = shopSettingsMap.get("bill_message_font");
			String showTotalQuantitySettings = shopSettingsMap.get("show_total_quantity");
			String addMakingLaborColumn = shopSettingsMap.get("add_making_charge_column");
			
			 boolean addCustomerCreditAmountToBill = false;		        	
			 boolean addDiscountColumn = false;
			 boolean addQRCode = false;
	         boolean addShortUnit = false;
	         boolean addGSTNumber = false;
	         boolean showTotalQuantity = false;
	         
	         
	         if(showTotalQuantitySettings.equals("TRUE"))
	         {
	        	 showTotalQuantity = true;
	         }
	         
	         if(addCustCreditAmtSettings.equals("TRUE"))
	         {
	        	 addCustomerCreditAmountToBill = true;
	         }
			 if(addDiscountColumnString.equals("TRUE"))
			 {
				 addDiscountColumn = true;
			 }
			 if(addQRCodeString.equals("TRUE"))
			 {
				 addQRCode = true;
			 }
			 if(addGSTNumberString.equals("TRUE"))
			 {
				 addGSTNumber = true;
			 }
    	
		String gstNum = (String)this.getSessionMap().get("shopgstnumber");
        	
         
            
        	response = ServletActionContext.getResponse();
			request = ServletActionContext.getRequest();
			
			this.setFigureList((ArrayList<Float>) this.getSessionMap().get("figureList"));
			
		String path= this.getRequest().getSession().getServletContext().getRealPath("/images/");
			
			
				try
				{
					 PDDocument document = new PDDocument(); 
						
					 PDPage page = null;
						int listSize = this.getFigureList().size();
						
						float pageHeight = 200.0F+(listSize*16.2F);
						
						if(addQRCode)
						{
							pageHeight = pageHeight + 10;
						}
						
					
					
					Float sum = 0.0F;
		        	
		        	for(Float i:this.getFigureList())
		        	{
		        		sum = sum + i;
		        	}
				PDRectangle pdRectangle = new PDRectangle(220.0F, 3200F);
				 page = new PDPage(pdRectangle);
				 
				 document.addPage(page);
				 
				 PDImageXObject pdImageQRCode = null;
				 Blob blob = (Blob) this.getSessionMap().get("qr_image_bolb");
				 
				 if(blob != null)
				 {
				 InputStream in = blob.getBinaryStream();
				 File qrFile = new File(path+"/"+shopId+"qr.jpeg");
				 FileOutputStream out = new FileOutputStream(qrFile);
				 byte[] buffer = new byte[1024];
				    int read;
				    while ((read = in.read(buffer)) != -1) {
				        out.write(buffer, 0, read);
				    }
				    
				    in.close();
				    out.close();
				    pdImageQRCode = PDImageXObject.createFromFile(path+"/"+shopId+"qr.jpeg", document);
				 }
				 
				 File fontFile  =  new File( request.getSession().getServletContext().getRealPath("/fonts/Nirmala.ttf"));
				 File fontFileBold  =  new File( request.getSession().getServletContext().getRealPath("/fonts/nirmala-bold.ttf"));
				 File fontFileKrutiBold  =  new File( request.getSession().getServletContext().getRealPath("/fonts/Kruti_Dev_100__Bold.ttf"));
					
				 TrueTypeFont ttf1 = new TTFParser().parse(fontFile);
				 PDFont fontMarathi = PDType0Font.load(document, ttf1, true);
				 
				 TrueTypeFont ttf2 = new TTFParser().parse(fontFileBold);
				 PDFont fontMarathiBold = PDType0Font.load(document, ttf2, true);
				 
				 TrueTypeFont ttf3 = new TTFParser().parse(fontFileKrutiBold);
				 PDFont fontMarathiKrutiBold = PDType0Font.load(document, ttf3, true);
				 
		         PDPageContentStream contentStream = new PDPageContentStream(document, page);
		         
		         
		         Table header;
		         Table billInfoTable;
		         Table itemInfo;
		        
		         
		         TableBuilder tableHeaderBuilder = Table.builder()
			                .addColumnsOfWidth(200)				                
			                .font(HELVETICA)
			                .borderColor(Color.BLACK)
			                .horizontalAlignment(CENTER);
		         
		     
		         
		         Row dairyNameHeader = Row.builder()
			                .add(TextCell.builder().text((String)this.getSessionMap().get("shopname2")).horizontalAlignment(CENTER).borderWidth(0).lineSpacing(0.5F).build())				               
			                .backgroundColor(WHITE)
			                .textColor(Color.BLACK)
			                .font(fontMarathiKrutiBold).fontSize(17)				              
			                .horizontalAlignment(CENTER)
			                .build();
		         
		         Row addressRow1 = Row.builder()
			                .add(TextCell.builder().text((String)this.getSessionMap().get("shopbillAddress")).horizontalAlignment(CENTER).borderWidth(0).lineSpacing(0.5F).build())				               
			                .backgroundColor(WHITE)
			                .textColor(Color.BLACK)
			                .font(fontMarathiKrutiBold).fontSize(11)				              
			                .horizontalAlignment(CENTER)
			                .build();
		         
		         Row addressRow2 = Row.builder()
			                .add(TextCell.builder()
			                		.text("Mo:"+(String)this.getSessionMap().get("shopcustcarenumber"))
			                		.horizontalAlignment(CENTER).borderWidth(0).lineSpacing(0.5F).build())				               
			                .backgroundColor(WHITE)
			                .textColor(Color.BLACK)
			                .font(PDType1Font.HELVETICA_BOLD).fontSize(9)				              
			                .horizontalAlignment(CENTER)
			                .build();
		     
		         
		         
		         
		         
		         tableHeaderBuilder.addRow(dairyNameHeader);
		         tableHeaderBuilder.addRow(addressRow1);
		         tableHeaderBuilder.addRow(addressRow2);
		        
		         
		         header = tableHeaderBuilder.build();
		         
		         //tableHeaderBuilder.addRow(addressRow2);
		        
		         
		         header = tableHeaderBuilder.build();
		         
		         Date d = new Date();
		        	SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy");
		        	String billDateTime = dateFormat.format(d);
		         
		         TableBuilder tableBillInfoBuilder = Table.builder()
			                .addColumnsOfWidth(200)				                
			                .font(HELVETICA)
			                .borderColor(Color.BLACK)
			                .horizontalAlignment(CENTER);
		         
		         Row billInfoRow1 = Row.builder()
			               .add(TextCell.builder().text("तारीख–:"+billDateTime).fontSize(8).horizontalAlignment(CENTER).borderWidthTop(0.5F).lineSpacing(0.5F).build())				               
				            .backgroundColor(WHITE)
			                .textColor(Color.BLACK)
			                .font(fontMarathiBold).fontSize(10)				              
			                .horizontalAlignment(CENTER)
			                .build();
		         
		         
		         Row billInfoRow2 = Row.builder()
			               .add(TextCell.builder().text("Billed By: "+billedBy).horizontalAlignment(CENTER).borderWidth(0).lineSpacing(0.5F).build())				               
				            .backgroundColor(WHITE)
			                .textColor(Color.BLACK)
			                .font(fontMarathiBold).fontSize(10)				              
			                .horizontalAlignment(CENTER)
			                .build();
		         
		         tableBillInfoBuilder.addRow(billInfoRow1);
		         tableBillInfoBuilder.addRow(billInfoRow2);
		      
		          billInfoTable = tableBillInfoBuilder.build();
		          
		          
			         float startY = page.getMediaBox().getHeight()-2;
			         TableDrawer.builder()
		                .contentStream(contentStream)
		                .table(header)
		                .startX(5F)
		                .startY(startY)
		                .build()
		                .draw();
			         
			         float currectY = startY - 50;
			        
			         TableDrawer.builder()
		                .contentStream(contentStream)
		                .table(billInfoTable)
		                .startX(5F)
		                .startY(currectY)
		                .build()
		                .draw();
			         
			         currectY = currectY - 30;
			         float itemEndY = currectY-20;
		         
			         TableBuilder tableItemInfoBuilder = Table.builder()
				                .addColumnsOfWidth(80,120)				                
				                .font(HELVETICA)
				                .borderColor(Color.BLACK)
				                .horizontalAlignment(CENTER);
		          
			         Row itemInfoHeader = Row.builder()
				                .add(TextCell.builder().text("SR.NO").fontSize(11).horizontalAlignment(CENTER).borderWidthTop(0.5F).borderWidthBottom(0.5F).lineSpacing(1F).build())				               
				                .add(TextCell.builder().text("AMOUNT").fontSize(11).horizontalAlignment(CENTER).borderWidthTop(0.5F).borderWidthBottom(0.5F).lineSpacing(1F).build())				               
						        .backgroundColor(WHITE)
				                .textColor(Color.BLACK)
				                .font(fontMarathiBold)          
				                .horizontalAlignment(CENTER)
				                .build();
			         
			         
			         
			         
			         tableItemInfoBuilder.addRow(itemInfoHeader);
			     	
			         int size = this.getFigureList().size();
			         int srNo = 1;
						for(Float val : this.getFigureList())
						{
							 Row itemDetails = null;
							
							if(size == 1)
							{
								
								 itemDetails = Row.builder()
							                .add(TextCell.builder().text(""+srNo).horizontalAlignment(CENTER).borderWidth(0.0F).borderWidthBottom(0.5F).lineSpacing(0.0F).build())				               
							                .add(TextCell.builder().text(""+val).fontSize(10).horizontalAlignment(CENTER).borderWidth(0F).borderWidthBottom(0.5F).lineSpacing(0.2F).build())				               
							              .backgroundColor(WHITE)
							                .textColor(Color.BLACK)
							                .font(fontMarathiBold).fontSize(10)	
							                .height(16F)
							                .horizontalAlignment(CENTER)
							                .build();
							}else
							{
					         itemDetails = Row.builder()
						                .add(TextCell.builder().text(""+srNo).horizontalAlignment(CENTER).borderWidth(0.0F).lineSpacing(0.2F).build())				               
						                .add(TextCell.builder().text(""+val).fontSize(10).horizontalAlignment(CENTER).borderWidth(0F).lineSpacing(0.2F).build())				               
						               .backgroundColor(WHITE)
						                .textColor(Color.BLACK)
						                .height(16F)
						                .font(fontMarathiBold).fontSize(10)				              
						                .horizontalAlignment(CENTER)
						                .build();
							}
						
					         tableItemInfoBuilder.addRow(itemDetails);
					         
					         size--;
					         srNo++;
					       
					        	 itemEndY = itemEndY - 16.2F;
					         
					         
						}
						itemInfo = tableItemInfoBuilder.build();
						
						
						 Table bottomInfo;
						 TableBuilder tableBottomInfoBuilder;
						
						  
						   tableBottomInfoBuilder = Table.builder()
					                .addColumnsOfWidth(100,100)				                
					                .font(HELVETICA)
					                .borderColor(Color.BLACK)
					                .horizontalAlignment(CENTER);
				         
								  
						
							  
					         Row itemTotalItemsInfo = Row.builder()
						                .add(TextCell.builder().text(",dq.k oLrq%").font(fontMarathiKrutiBold).fontSize(12).horizontalAlignment(RIGHT).borderWidthTop(0.5F).borderWidthBottom(0.5F).lineSpacing(2F).build())				               
						                .add(TextCell.builder().text(""+listSize).font(fontMarathiBold).fontSize(15).horizontalAlignment(LEFT).borderWidthTop(0.5F).borderWidthBottom(0.5F).lineSpacing(2F).build())				               
						                .backgroundColor(WHITE)
						                .textColor(Color.BLACK)
						                .font(fontMarathiKrutiBold)	
						                .fontSize(15)
						                .horizontalAlignment(CENTER)
						                .build();
					         Row itemTotalInfo = Row.builder()
						                .add(TextCell.builder().text("jDde%").font(fontMarathiKrutiBold).fontSize(12).horizontalAlignment(RIGHT).borderWidthTop(0.5F).borderWidthBottom(0.5F).lineSpacing(2F).build())				               
						                .add(TextCell.builder().text(sum+" \u20B9").font(fontMarathiBold).fontSize(15).horizontalAlignment(LEFT).borderWidthTop(0.5F).borderWidthBottom(0.5F).lineSpacing(2F).build())				               
							             .backgroundColor(WHITE)
						                .textColor(Color.BLACK)
						                .horizontalAlignment(CENTER)
						                .build();
					    
					         
					         
					         tableBottomInfoBuilder.addRow(itemTotalItemsInfo);
					         tableBottomInfoBuilder.addRow(itemTotalInfo);
					         bottomInfo = tableBottomInfoBuilder.build();
						
		          
					    
				          Table conmpanyInfo;
				          
				         TableBuilder tableCompanyInfoBuilder = Table.builder()
					                .addColumnsOfWidth(200)				                
					                .font(HELVETICA)
					                .borderColor(Color.BLACK)
					                .horizontalAlignment(CENTER);
				         
				         Row companyInfoRow1 = Row.builder()
					                .add(TextCell.builder().text("Developed By: Real Link Web Tech:8208064913").horizontalAlignment(CENTER).borderWidthTop(0.5F).lineSpacing(1F).build())				               
					                .backgroundColor(WHITE)
					                .textColor(Color.BLACK)
					                .font(fontMarathiBold).fontSize(8)				              
					                .horizontalAlignment(CENTER)
					                .build();
				         tableCompanyInfoBuilder.addRow(companyInfoRow1);
				         
				         conmpanyInfo = tableCompanyInfoBuilder.build();
				        
				         
				        
				           TableDrawer.builder()
			                .contentStream(contentStream)
			                .table(itemInfo)
			                .startX(5F)
			                .startY(currectY)
			                .build()
			                .draw();
				       
				         
				           
				         if(addQRCode)
				         {
				        	 
				        	 TableDrawer.builder()
				                .contentStream(contentStream)
				                .table(bottomInfo)
				                .startX(5F)
				                .startY(itemEndY)
				                .build()
				                .draw();
				        	 
				        	
				        	 
				        	 itemEndY = itemEndY - 50;
					         
					         TableDrawer.builder()
				                .contentStream(contentStream)
				                .table(conmpanyInfo)
				                .startX(0F)
				                .startY(itemEndY)
				                .build()
				                .draw();
					         
					         contentStream.drawImage(pdImageQRCode, 55, itemEndY-100, 75, 75);
				         }
				         else
				         {
				        	
				        	 
				        	 TableDrawer.builder()
				                .contentStream(contentStream)
				                .table(bottomInfo)
				                .startX(5F)
				                .startY(itemEndY)
				                .build()
				                .draw();		        	 
				        	
					         TableDrawer.builder()
				                .contentStream(contentStream)
				                .table(conmpanyInfo)
				                .startX(5F)
				                .startY(itemEndY-50)
				                .build()
				                .draw();
				         }
				         
				        
				         
				      
				         contentStream.close();
						 	document.save(path+"/bill.pdf");
					        document.close();
					        
					        

							response.setHeader("Content-disposition", "inline; filename=bill.pdf");
							response.setContentType("application/pdf");
							FileInputStream fileInputStream = new FileInputStream(path+"/bill.pdf");
							PrintWriter out = response.getWriter();  
							int bytes;
							while ((bytes = fileInputStream.read()) != -1) {
								out.write(bytes);
							}
							fileInputStream.close();
							out.flush();
							out.close();
							ttf1.close();
							ttf2.close();
							ttf3.close();
	          
				}catch (Exception e) {
					// TODO: handle exception
					e.printStackTrace();
				}

        }
	}
	
	public HttpServletRequest getRequest() {
		return request;
	}

	public void setRequest(HttpServletRequest request) {
		this.request = request;
	}

	public HttpServletResponse getResponse() {
		return response;
	}

	public void setResponse(HttpServletResponse response) {
		this.response = response;
	}

	public ArrayList<Float> getFigureList() {
		return figureList;
	}

	public void setFigureList(ArrayList<Float> figureList) {
		this.figureList = figureList;
	}

	public SessionMap<String, Object> getSessionMap() {
		return sessionMap;
	}
	
	public void setSessionMap(SessionMap<String, Object> sessionMap) {
		this.sessionMap = sessionMap;
	}
	
	public void setSession(Map<String, Object> map) {  
	    sessionMap=(SessionMap<String, Object>)map;  
	}
	     

}
