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.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

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

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.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.reallinkbilling.DAO.CustomerPaymentReminderDetailsDAO;
import com.reallinkbilling.db.GetDBConnection;
import com.reallinkbilling.DAO.LaborDetailsListDAO;



import com.opensymphony.xwork2.ActionSupport;

public class DownloadCustomerPaymentReminder extends ActionSupport implements SessionAware{

	/**
	 * 
	 */
	private static final long serialVersionUID = 899359324049622561L;
	private HttpSession session;
	
	public HttpServletRequest request;
	public HttpServletResponse response;
	private SessionMap<String,Object> sessionMap;
	 ArrayList<CustomerPaymentReminderDetailsDAO> customerPaymentReminderList;
		
	 
	 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 PADDING5 = 5f;
	    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;
	
	
	
	public void download(){
	
			this.setSession(ServletActionContext.getRequest().getSession(false)); 
		
	        if(this.getSession()==null || this.getSession().getAttribute("login")==null){ 
	        	addActionMessage("Please Login First !!!");
	         }  
	        else{
	        
	    		
	    		String shopId = (String) this.getSessionMap().get("shopId");
	    		String shopCode = (String) this.getSessionMap().get("shopCode");

	        	Connection connection = null;
				PreparedStatement preparedStatement= null;
				ResultSet  resultSet = null;
				
				String sql = "";
				String db = (String)  this.getSessionMap().get("db");
				
				try
				{
					this.setCustomerPaymentReminderList((ArrayList<CustomerPaymentReminderDetailsDAO>) this.getSessionMap().get("customerpaymentnotificationlist"));
					
					
					@SuppressWarnings("unchecked")
					String crusherName = (String) this.getSessionMap().get("shopnameenglish");
				    
					
					
					response = ServletActionContext.getResponse();
					request = ServletActionContext.getRequest();
					
					String path=	request.getSession().getServletContext().getRealPath("/images/");
					
				
					PDDocument document = new PDDocument(); 
					PDPage page = null;
					
					 page = new PDPage(PDRectangle.A4);
					
					 
					 document.addPage(page);
					 
					 
			         PDPageContentStream contentStream = new PDPageContentStream(document, page);
			         
			         File fontFile  =  new File( request.getSession().getServletContext().getRealPath("/fonts/Nirmala.ttf"));
			 		
					 TrueTypeFont ttf1 = new TTFParser().parse(fontFile);
					 PDFont fontMarathi = PDType0Font.load(document, ttf1, true);
					 
					 
			         int pageCount = 1;
			         
			         Table header;
			         
			         
			         
			         
			         TableBuilder tableHeaderBuilder = Table.builder()
				                .addColumnsOfWidth(585)				                
				                .font(HELVETICA)
				                .borderColor(Color.BLACK)
				                .horizontalAlignment(CENTER);
			         
			         Row dairyNameHeader = Row.builder()
				                .add(TextCell.builder().text(crusherName).horizontalAlignment(CENTER).borderWidth(0).lineSpacing(10F).build())				               
				                .backgroundColor(WHITE)
				                .textColor(Color.BLACK)
				                .font(PDType1Font.HELVETICA_BOLD).fontSize(16)				              
				                .horizontalAlignment(CENTER)
				                .build();
			         
			      
			         Row reportInfo1 = Row.builder()
				                .add(TextCell.builder()
		                		.text("Customer Payment Reminder Notification List : Page No: "+pageCount)
		                		.horizontalAlignment(CENTER).borderWidth(0).lineSpacing(10F).build())				               
				                .backgroundColor(WHITE)
				                .textColor(Color.BLACK)
				                .font(PDType1Font.HELVETICA_BOLD).fontSize(10)				              
				                .horizontalAlignment(CENTER)
				                .build();
			         
			         
			         tableHeaderBuilder.addRow(dairyNameHeader);
			         tableHeaderBuilder.addRow(reportInfo1);
			       
			         
			         header = tableHeaderBuilder.build();
			         
			         
			         
			         float startY = page.getMediaBox().getHeight() - PADDING20;
			         TableDrawer.builder()
		                .contentStream(contentStream)
		                .table(header)
		                .startX(PADDING30)
		                .startY(startY)
		                .build()
		                .draw();
			         
			           
			         
			         Table custListHeaderInfo;
			         TableBuilder custInfoBuilder = Table.builder()
				                .addColumnsOfWidth(80,125,70,60,80,170)				                
				                .font(HELVETICA)
				                .borderWidth(0.5F)
				                .borderColor(Color.BLACK)
				                .horizontalAlignment(CENTER);
			         
			         
			         Row custInfoTableHeader = Row.builder()
			        		 .add(TextCell.builder().text("Add Date").horizontalAlignment(LEFT).borderWidth(0.5F).lineSpacing(1F).build())				                
					        	.add(TextCell.builder().text("Customer Name").horizontalAlignment(CENTER).borderWidth(0.5F).lineSpacing(1F).build())
					            .add(TextCell.builder().text("Mobile").horizontalAlignment(LEFT).borderWidth(0.5F).lineSpacing(1F).build())
					            .add(TextCell.builder().text("Credit Amt").horizontalAlignment(LEFT).borderWidth(0.5F).lineSpacing(1F).build())
					            .add(TextCell.builder().text("Promise Date").horizontalAlignment(LEFT).borderWidth(0.5F).lineSpacing(1F).build())
				                .add(TextCell.builder().text("Comments").horizontalAlignment(CENTER).borderWidth(0.5F).lineSpacing(1F).build())
				                .backgroundColor(Color.LIGHT_GRAY)
				                .textColor(Color.BLACK)
				                .font(PDType1Font.HELVETICA_BOLD).fontSize(9)				              
				                .horizontalAlignment(CENTER)
				                .build();
			         
			         custInfoBuilder.addRow(custInfoTableHeader);
			         custListHeaderInfo = custInfoBuilder.build();
			        		
			        		 TableDrawer.builder()
				                .contentStream(contentStream)
				                .table(custListHeaderInfo)
				                .startX(PADDING5)
				                .startY(startY-50)
				                .build()
				                .draw();
			         
			        		 float currentY =  startY;
			        		
			        		 Table custDetailsTable = null;
				        	 
					         TableBuilder custDetailsTableBuilder = Table.builder()
					        		 .addColumnsOfWidth(80,125,70,60,80,170)				                
						                 .font(HELVETICA)
						                .borderWidth(0.5F)
						                .borderColor(Color.BLACK)
						                .horizontalAlignment(CENTER);
					         
					         double totalCreditAmount = 0;
				        	 			        		 
			        		 for(CustomerPaymentReminderDetailsDAO dao:getCustomerPaymentReminderList())
					         {  
					        
			        			 totalCreditAmount += dao.getOutstandingAmount();
					        	 
						         if(currentY < 200)
						         {
						        	 
						        	 custDetailsTable = custDetailsTableBuilder.build();
						        	 TableDrawer.builder()
						                .contentStream(contentStream)
						                .table(custDetailsTable)
						                .startX(PADDING5)
						                .startY(startY-65)
						                .build()
						                .draw();
						        	 
						        	 custDetailsTable = null;
						        	 custDetailsTableBuilder = null;
						        	 
						        	  custDetailsTableBuilder = Table.builder()
						        			  .addColumnsOfWidth(80,125,70,60,80,170)				                
								                .font(HELVETICA)
								                .borderWidth(0.5F)
								                .borderColor(Color.BLACK)
								                .horizontalAlignment(CENTER);
						        	 
						        	 pageCount++;
						        	 contentStream.close();
						        	PDPage newPage = new PDPage(PDRectangle.A4);
						        	 contentStream = new PDPageContentStream(document,newPage);
						        	
						        	currentY = startY;
						             document.addPage( newPage );
						             
						             
						             
						             Table headerOtherPage;
							         
							         
							         
							         
							         TableBuilder tableHeaderBuilderOtherPage = Table.builder()
								                .addColumnsOfWidth(585)				                
								                .font(HELVETICA)
								                .borderColor(Color.BLACK)
								                .horizontalAlignment(CENTER);
							         
							         Row dairyNameHeaderOtherPage = Row.builder()
								                .add(TextCell.builder().text(crusherName).horizontalAlignment(CENTER).borderWidth(0).lineSpacing(10F).build())				               
								                .backgroundColor(WHITE)
								                .textColor(Color.BLACK)
								                .font(PDType1Font.HELVETICA_BOLD).fontSize(16)				              
								                .horizontalAlignment(CENTER)
								                .build();
							         
							         
							         Row reportInfo1OtherPage = Row.builder()
								                .add(TextCell.builder()
								                		.text("Customer Payment Reminder Notification List : Page No: "+pageCount)
								                		.horizontalAlignment(CENTER).borderWidth(0).lineSpacing(10F).build())				               
								                .backgroundColor(WHITE)
								                .textColor(Color.BLACK)
								                .font(PDType1Font.HELVETICA_BOLD).fontSize(12)				              
								                .horizontalAlignment(CENTER)
								                .build();
							       
							         
							         
							         tableHeaderBuilderOtherPage.addRow(dairyNameHeaderOtherPage);
							         tableHeaderBuilderOtherPage.addRow(reportInfo1OtherPage);
							       
							         
							         headerOtherPage = tableHeaderBuilderOtherPage.build();
							         
							         TableDrawer.builder()
						                .contentStream(contentStream)
						                .table(headerOtherPage)
						                .startX(PADDING30)
						                .startY(startY)
						                .build()
						                .draw();
							         
							         
						             
						             TableDrawer.builder()
						                .contentStream(contentStream)
						                .table(custListHeaderInfo)
						                .startX(PADDING5)
						                .startY(startY-50)
						                .build()
						                .draw();
						             currentY = currentY + 55;
						         }
						        
						         
						         Row custInfoRow = Row.builder()
							                .add(TextCell.builder().text(""+dao.getPaymentReminderAddDate()).horizontalAlignment(LEFT).borderWidth(0.5F).lineSpacing(0.2F).build())				               
							                .add(TextCell.builder().text(""+dao.getCustomerName()).horizontalAlignment(LEFT).borderWidth(0.5F).lineSpacing(0.2F).build())				               
							                .add(TextCell.builder().text(""+dao.getCustomerMobileNumber()).horizontalAlignment(CENTER).borderWidth(0.5F).lineSpacing(0.2F).build())
							                .add(TextCell.builder().text(""+dao.getOutstandingAmount()).horizontalAlignment(CENTER).borderWidth(0.5F).lineSpacing(0.2F).build())
							                .add(TextCell.builder().text(""+dao.getPaymentPromiseDate()).horizontalAlignment(CENTER).borderWidth(0.5F).lineSpacing(0.2F).build())
							                .add(TextCell.builder().text(""+dao.getComments()).horizontalAlignment(LEFT).borderWidth(0.5F).lineSpacing(0.2F).build())
							                .backgroundColor(Color.WHITE)
							                .textColor(Color.BLACK)
							                .font(fontMarathi).fontSize(8)				              
							                .horizontalAlignment(CENTER)
							                .height(20F)
							                .build();
						         
						         custDetailsTableBuilder.addRow(custInfoRow);
						         
						         currentY = currentY - 20;
					        	 
					        	
					         }
			        		 
			        		 
			        		 Row creditTotalInfo = Row.builder()
				        			  	.add(TextCell.builder().text("Total").colSpan(3).horizontalAlignment(RIGHT).borderWidth(0.5F).lineSpacing(1F).build())				                
				        			  	.add(TextCell.builder().text(""+totalCreditAmount).horizontalAlignment(LEFT).fontSize(9).borderWidth(0.5F).lineSpacing(1F).build())
				        			  	.add(TextCell.builder().text("").colSpan(2).horizontalAlignment(RIGHT).borderWidth(0.5F).lineSpacing(1F).build())				                
				        			  	.backgroundColor(Color.WHITE)
						                .textColor(Color.BLACK)
						                .font(PDType1Font.HELVETICA_BOLD)
						                .fontSize(9)				              
						                .horizontalAlignment(CENTER)
						                .height(25F)					                
						                .build();
			        		 custDetailsTableBuilder.addRow(creditTotalInfo);
			        		 
			        		 
			        		 
			        		 if(pageCount==1 || custDetailsTableBuilder != null)
			        		 {
			        		 

				        	 custDetailsTable = custDetailsTableBuilder.build();
				        	 
				        	 TableDrawer.builder()
				                .contentStream(contentStream)
				                .table(custDetailsTable)
				                .startX(PADDING5)
				                .startY(startY-65)
				                .build()
				                .draw();
			        		 }

					         	contentStream.close();
							 	document.save(path+"/customer-payment-reminder-notification-list.pdf");
						        document.close();
						        
						        

								response.setHeader("Content-disposition", "inline; filename=customer-payment-reminder-notification-list.pdf");
								response.setContentType("application/pdf");
								FileInputStream fileInputStream = new FileInputStream(path+"/customer-payment-reminder-notification-list.pdf");
								PrintWriter out = response.getWriter();  
								int bytes;
								while ((bytes = fileInputStream.read()) != -1) {
									out.write(bytes);
								}
								fileInputStream.close();
								out.flush();
								out.close();
								ttf1.close();
					
				}
				catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}catch(Exception e)
				{
					e.printStackTrace();
				}
				finally {
					
					
					if(resultSet !=null)
					{
						try {resultSet.close(); resultSet = null;} catch (SQLException e) {}
					}
					if(preparedStatement != null)
					{
						try {preparedStatement.close(); preparedStatement = null;} catch (SQLException e) {}
					}
					if(connection != null)
					{
						
						try {connection.close();
						 connection = null;
						}catch (SQLException e) {}
					}
				
			}
        }
}



	public HttpSession getSession() {
		return session;
	}



	public void setSession(HttpSession session) {
		this.session = session;
	}
      

	public SessionMap<String, Object> getSessionMap() {
		return sessionMap;
	}

	public void setSessionMap(SessionMap<String, Object> sessionMap) {
		this.sessionMap = sessionMap;
	}

	@Override  
	public void setSession(Map<String, Object> map) {  
	    sessionMap=(SessionMap<String, Object>)map;  
	}



	public ArrayList<CustomerPaymentReminderDetailsDAO> getCustomerPaymentReminderList() {
		return customerPaymentReminderList;
	}



	public void setCustomerPaymentReminderList(ArrayList<CustomerPaymentReminderDetailsDAO> customerPaymentReminderList) {
		this.customerPaymentReminderList = customerPaymentReminderList;
	}
	
	
    
}

