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.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.opensymphony.xwork2.ActionSupport;
import com.reallinkbilling.DAO.CustomerListDAO;
import com.reallinkbilling.db.GetDBConnection;

public class DownloadListOfCustomer extends ActionSupport implements SessionAware{

	private static final long serialVersionUID = 899359324049622561L;
	private HttpSession session;
	
	public HttpServletRequest request;
	public HttpServletResponse response;
	private SessionMap<String,Object> sessionMap;
	  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;
	
	
	
	public void download(){
	
			this.setSession(ServletActionContext.getRequest().getSession(false)); 
		
	        if(this.getSession()==null || this.getSession().getAttribute("login")==null){ 
	        	addActionMessage("Please Login First !!!");
	         }  
	        else{
	        	
	        	Connection connection = null;
				PreparedStatement preparedStatement= null;
				ResultSet  resultSet = null;
				
				String sql = "";
				String db = (String)  this.getSessionMap().get("db");
				
				try
				{
					
					connection = GetDBConnection.getDBConnection(db);
					
					//System.out.println("listofcustomer");
					
					
					String shopId = (String) this.getSessionMap().get("shopId");
					String shopCode = (String) this.getSessionMap().get("shopCode");
					
					//System.out.println("shopId = "+shopId);
					//System.out.println("shopCode = "+shopCode);
					
					sql = "SELECT "
							+ "customer_id ,"
	       					+ "customer_name,"
	       					+ "billing_address,"
	       					+ "mobile_number,"
	       					+ "gst_number "
	       					+ "FROM "
	       					+ "shop_customer_master "
	       					+ "WHERE "
	       					+ "shop_id = ? "
	       					+ "AND "
	       					+ "shop_code = ? "
	       					+"ORDER BY customer_name";
					
					preparedStatement = connection.prepareStatement(sql);
					preparedStatement.setString(1, shopId);
					preparedStatement.setString(2, shopCode);
					
					resultSet = preparedStatement.executeQuery();
					
					List<CustomerListDAO> custDAOList = new ArrayList<CustomerListDAO>();
					
					while(resultSet.next())
					{
						//System.out.println("Query Executed Successfully");
						
						CustomerListDAO custDao = new CustomerListDAO();
						
						custDao.setCustomerId(resultSet.getString(1));
						//custDao.setAddDate(resultSet.getString(2));;
						custDao.setCustomerName(resultSet.getString(2));
						custDao.setBillingAddress(resultSet.getString(3));
						custDao.setMobileNumber(resultSet.getString(4));
						custDao.setGstNumber(resultSet.getString(5));
						custDAOList.add(custDao);
					}
				   
					if(resultSet != null)
					{
						resultSet.close();
						resultSet = null;
					}
					if(preparedStatement != null)
					{
						preparedStatement.close();
						preparedStatement = null;
					}
					if(connection != null)
					{
						connection.close();
					}
					
					response = ServletActionContext.getResponse();
					request = ServletActionContext.getRequest();
					
					String path=	request.getSession().getServletContext().getRealPath("/images/");
					
					//System.out.println(this.getSessionMap().keySet());
					
					String shopName = (String)  this.getSessionMap().get("shopnameenglish");
					String shopaddresseng = (String)  this.getSessionMap().get("shopaddresseng");
					
					PDDocument document = new PDDocument(); 
					PDPage page = null;
					
					 page = new PDPage(new PDRectangle(PDRectangle.A4.getHeight(),PDRectangle.A4.getWidth()));
					
					 
					 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(550)				                
				                .font(HELVETICA)
				                .borderColor(Color.BLACK)
				                .horizontalAlignment(CENTER);
			         
			      
			         
			         			Row shopNameHeader = Row.builder()
				                .add(TextCell.builder().text(shopName+","+shopaddresseng).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 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(shopNameHeader);
			         tableHeaderBuilder.addRow(reportInfo1);
			       
			         
			         header = tableHeaderBuilder.build();
			         
			         float pagewidth = page.getMediaBox().getWidth();
			         float headerWidth = 550;
			         float headerStartX = (pagewidth -headerWidth )/2;
			         
			         float startY = page.getMediaBox().getHeight() - PADDING20;
			         TableDrawer.builder()
		                .contentStream(contentStream)
		                .table(header)
		                .startX(headerStartX)
		                .startY(startY)
		                .build()
		                .draw();
			         
			         
			         
			         Table custListHeaderInfo;
			         TableBuilder custInfoBuilder = Table.builder()
				                .addColumnsOfWidth(50,220,90,280,100)			                
				                .font(HELVETICA)
				                .borderWidth(0.5F)
				                .borderColor(Color.BLACK)
				                .horizontalAlignment(CENTER);
			         
			         
			         Row custInfoTableHeader = Row.builder()
					           	.add(TextCell.builder().text("Sr No").horizontalAlignment(CENTER).borderWidth(0.5F).lineSpacing(1F).build())				               
				                .add(TextCell.builder().text("Customer Name").horizontalAlignment(LEFT).borderWidth(0.5F).lineSpacing(1F).build())
				                .add(TextCell.builder().text("Mobile").horizontalAlignment(CENTER).borderWidth(0.5F).lineSpacing(1F).build())
				                .add(TextCell.builder().text("Address").horizontalAlignment(CENTER).borderWidth(0.5F).lineSpacing(1F).build())
				                .add(TextCell.builder().text("GST NO").horizontalAlignment(CENTER).borderWidth(0.5F).lineSpacing(1F).build())
				                .backgroundColor(Color.LIGHT_GRAY)
				                .textColor(Color.BLACK)
				                .font(PDType1Font.HELVETICA_BOLD).fontSize(10)				              
				                .horizontalAlignment(CENTER)
				                .build();
			         
			         custInfoBuilder.addRow(custInfoTableHeader);
			         custListHeaderInfo = custInfoBuilder.build();
			        
			        // tablewidth = addition of columnof width
			       
			         float StartX1 = (pagewidth -740 )/2;
			        		
			        		 TableDrawer.builder()
				                .contentStream(contentStream)
				                .table(custListHeaderInfo)
				                .startX(StartX1)
				                .startY(startY-50)
				                .build()
				                .draw();
			         
			        		 float currentY =  startY;
			        		
			        		 Table custDetailsTable = null;
				        	 
					         TableBuilder custDetailsTableBuilder = Table.builder()
						                .addColumnsOfWidth(50,220,90,280,100)				                
						                .font(HELVETICA)
						                .borderWidth(0.5F)
						                .borderColor(Color.BLACK)
						                .horizontalAlignment(CENTER);
					         
					         int srNo = 1;
				        	 			        		 
			        		 for(CustomerListDAO dao:custDAOList)
					         {  
					        
					        	 
						         if(currentY < 10)
						         {
						        	 
						        	 custDetailsTable = custDetailsTableBuilder.build();
						        	 TableDrawer.builder()
						                .contentStream(contentStream)
						                .table(custDetailsTable)
						                .startX(StartX1)
						                .startY(startY-65)
						                .build()
						                .draw();
						        	 
						        	 custDetailsTable = null;
						        	 custDetailsTableBuilder = null;
						        	 
						        	  custDetailsTableBuilder = Table.builder()
								                .addColumnsOfWidth(50,220,90,280,100)			                
								                .font(HELVETICA)
								                .borderWidth(0.5F)
								                .borderColor(Color.BLACK)
								                .horizontalAlignment(CENTER);
						        	 
						        	 pageCount++;
						        	 contentStream.close();
						        	 
						        	 // new page 
						        	PDPage newPage = new PDPage(new PDRectangle(PDRectangle.A4.getHeight(),PDRectangle.A4.getWidth()));
						        	 contentStream = new PDPageContentStream(document,newPage);
						        	
						        	currentY = startY;
						             document.addPage( newPage );
						             
						             
						             
						             Table headerOtherPage;
							         
							         
							         
							         
							         TableBuilder tableHeaderBuilderOtherPage = Table.builder()
								                .addColumnsOfWidth(550)				                
								                .font(HELVETICA)
								                .borderColor(Color.BLACK)
								                .horizontalAlignment(CENTER);
							         
							         Row shopNameHeaderOtherPage = Row.builder()
								                .add(TextCell.builder().text(shopName+","+shopaddresseng).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 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(shopNameHeaderOtherPage);
							         tableHeaderBuilderOtherPage.addRow(reportInfo1OtherPage);
							       
							         
							         headerOtherPage = tableHeaderBuilderOtherPage.build();
							         
							         
							         
							         TableDrawer.builder()
						                .contentStream(contentStream)
						                .table(headerOtherPage)
						                .startX(headerStartX)
						                .startY(startY)
						                .build()
						                .draw();
							         
							         
						             
						             TableDrawer.builder()
						                .contentStream(contentStream)
						                .table(custListHeaderInfo)
						                .startX(StartX1)
						                .startY(startY-50)
						                .build()
						                .draw();
						             currentY = currentY + 55;
						         }
						        
						         
						         Row custInfoRow = Row.builder()
								           	.add(TextCell.builder().text(String.valueOf(srNo)).horizontalAlignment(CENTER).borderWidth(0.5F).lineSpacing(1F).build())				               
							                .add(TextCell.builder().text(dao.getCustomerName()).horizontalAlignment(LEFT).borderWidth(0.5F).lineSpacing(1F).build())
							                .add(TextCell.builder().text(dao.getMobileNumber()).horizontalAlignment(CENTER).borderWidth(0.5F).lineSpacing(1F).build())
							                .add(TextCell.builder().text(dao.getBillingAddress()).horizontalAlignment(LEFT).borderWidth(0.5F).lineSpacing(1F).build())
							                .add(TextCell.builder().text(dao.getGstNumber()).horizontalAlignment(CENTER).borderWidth(0.5F).lineSpacing(1F).build())
							                .backgroundColor(Color.WHITE)
							                .textColor(Color.BLACK)
							                .font(fontMarathi).fontSize(10)				              
							                .horizontalAlignment(CENTER)
							              // .height(20F)
							                .build();
						         
						         custDetailsTableBuilder.addRow(custInfoRow);
						         
						         currentY = currentY - 20;
						         
						         srNo++;
					        	 
					        	
					         }
			        		 
			        		 if(pageCount==1 || custDetailsTableBuilder != null)
			        		 {

				        	 custDetailsTable = custDetailsTableBuilder.build();
				        	 TableDrawer.builder()
				                .contentStream(contentStream)
				                .table(custDetailsTable)
				                .startX(StartX1)
				                .startY(startY-65)
				                .build()
				                .draw();
			        		 }

					         	contentStream.close();
							 	document.save(path+"/customer-list.pdf");
						        document.close();
						        
						        

								response.setHeader("Content-disposition", "inline; filename=customer-list.pdf");
								response.setContentType("application/pdf");
								FileInputStream fileInputStream = new FileInputStream(path+"/customer-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 (SQLException e) 
				{


					addActionError(e.getErrorCode()+" || "+e.getMessage() +" || Collection details could not be found !");


				} 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;  
	}
	
	
}
