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.EmployeeDetailsListDAO;
import com.reallinkbilling.db.GetDBConnection;
import com.opensymphony.xwork2.ActionSupport;

public class DownloadListOfEmployee 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 downloadEmployeeList(){
	
			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
				{
					
					connection = GetDBConnection.getDBConnection(db);
					HashMap<String,String> designationList = (HashMap<String, String>) this.getSessionMap().get("designationlist");
					
					sql = "SELECT "
							+ "emp.employee_id,"							
							+ "emp.employee_name,"
							+ "emp.employee_mobile_number,"
							+ "esm.employee_salary_type,"
							+ "esm.employee_salary_amount,"
							+ "emp.employee_designation "
							+ "FROM "
							+ "shop_employee_master AS emp "
							+ "INNER JOIN "
							+ "shop_employee_salary_details AS esm "
							+ "ON "
							+ "emp.employee_id = esm.employee_id "
							+ "AND "
							+ "emp.shop_id = ? "
							+ "AND "
							+ "emp.shop_code = ? "
							+ "AND "
							+ "esm.shop_id = ? "
							+ "AND "
							+ "esm.shop_code = ? "
							+ "ORDER BY emp.employee_name";
					
					preparedStatement = connection.prepareStatement(sql);
					
					preparedStatement.setString(1, shopId);
					preparedStatement.setString(2, shopCode);
					preparedStatement.setString(3, shopId);
					preparedStatement.setString(4, shopCode);
					
					resultSet = preparedStatement.executeQuery();
					
					List<EmployeeDetailsListDAO> employeeDAOList = new ArrayList<EmployeeDetailsListDAO>();
					
					while(resultSet.next())
					{
						EmployeeDetailsListDAO employeeDao = new EmployeeDetailsListDAO();
						employeeDao.setEmployeeId(resultSet.getString(1));
						employeeDao.setEmployeeName(resultSet.getString(2));
						employeeDao.setEmployeeMobile(resultSet.getString(3));
						employeeDao.setSalaryType(resultSet.getString(4));
						employeeDao.setSalaryAmount(resultSet.getString(5));
						employeeDao.setEmployeeDesignation(designationList.get(resultSet.getString(6)));
						
						employeeDAOList.add(employeeDao);
					}
				   
					if(resultSet != null)
					{
						resultSet.close();
						resultSet = null;
					}
					if(preparedStatement != null)
					{
						preparedStatement.close();
						preparedStatement = null;
					}
					if(connection != null)
					{
						connection.close();
						connection = null;
					}
					
					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(550)				                
				                .font(HELVETICA)
				                .borderColor(Color.BLACK)
				                .horizontalAlignment(CENTER);
			         
			         Row dairyNameHeader = Row.builder()
				                .add(TextCell.builder().text((String)this.getSessionMap().get("shopnameenglish")).horizontalAlignment(CENTER).borderWidth(0).lineSpacing(10F).build())				               
				                .backgroundColor(WHITE)
				                .textColor(Color.BLACK)
				                .font(PDType1Font.HELVETICA_BOLD).fontSize(20)				              
				                .horizontalAlignment(CENTER)
				                .build();
			         
			      
			         Row reportInfo1 = Row.builder()
				                .add(TextCell.builder()
		                		.text("Employee Details 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(180,80,100,100,80)				                
				                .font(HELVETICA)
				                .borderWidth(0.5F)
				                .borderColor(Color.BLACK)
				                .horizontalAlignment(CENTER);
			         
			         
			         Row custInfoTableHeader = Row.builder()
			        		 	.add(TextCell.builder().text("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("Designation").horizontalAlignment(CENTER).borderWidth(0.5F).lineSpacing(1F).build())
				                .add(TextCell.builder().text("Salary Type").horizontalAlignment(CENTER).borderWidth(0.5F).lineSpacing(1F).build())
				                .add(TextCell.builder().text("Salary Amount").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();
			        		
			        		 TableDrawer.builder()
				                .contentStream(contentStream)
				                .table(custListHeaderInfo)
				                .startX(PADDING20)
				                .startY(startY-50)
				                .build()
				                .draw();
			         
			        		 float currentY =  startY;
			        		
			        		 Table custDetailsTable = null;
				        	 
					         TableBuilder custDetailsTableBuilder = Table.builder()
					        		 .addColumnsOfWidth(180,80,100,100,80)						                
						                .font(HELVETICA)
						                .borderWidth(0.5F)
						                .borderColor(Color.BLACK)
						                .horizontalAlignment(CENTER);
				        	 			        		 
			        		 for(EmployeeDetailsListDAO dao:employeeDAOList)
					         {  
					        
					        	 
						         if(currentY < 200)
						         {
						        	 
						        	 custDetailsTable = custDetailsTableBuilder.build();
						        	 TableDrawer.builder()
						                .contentStream(contentStream)
						                .table(custDetailsTable)
						                .startX(PADDING20)
						                .startY(startY-65)
						                .build()
						                .draw();
						        	 
						        	 custDetailsTable = null;
						        	 custDetailsTableBuilder = null;
						        	 
						        	  custDetailsTableBuilder = Table.builder()
						        			  .addColumnsOfWidth(180,80,100,100,80)					                
								                .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(550)				                
								                .font(HELVETICA)
								                .borderColor(Color.BLACK)
								                .horizontalAlignment(CENTER);
							         
							         Row dairyNameHeaderOtherPage =  Row.builder()
								                .add(TextCell.builder().text((String)this.getSessionMap().get("shopnameenglish")).horizontalAlignment(CENTER).borderWidth(0).lineSpacing(10F).build())				               
								                .backgroundColor(WHITE)
								                .textColor(Color.BLACK)
								                .font(PDType1Font.HELVETICA_BOLD).fontSize(20)				              
								                .horizontalAlignment(CENTER)
								                .build();
							         
							         
							         
							         Row reportInfo1OtherPage = Row.builder()
								                .add(TextCell.builder()
								                		.text("Employee details 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(PADDING20)
						                .startY(startY-50)
						                .build()
						                .draw();
						             currentY = currentY + 55;
						         }
						        
						         
						         Row custInfoRow = Row.builder()
							                .add(TextCell.builder().text(dao.getEmployeeName()).horizontalAlignment(LEFT).borderWidth(0.5F).lineSpacing(10F).build())				               
							                .add(TextCell.builder().text(dao.getEmployeeMobile()).horizontalAlignment(CENTER).borderWidth(0.5F).lineSpacing(10F).build())
							                .add(TextCell.builder().text(dao.getEmployeeDesignation()).fontSize(8).horizontalAlignment(LEFT).borderWidth(0.5F).lineSpacing(10F).build())
								            .add(TextCell.builder().text(dao.getSalaryType()).horizontalAlignment(LEFT).borderWidth(0.5F).lineSpacing(10F).build())
							                .add(TextCell.builder().text(dao.getSalaryAmount()).horizontalAlignment(RIGHT).borderWidth(0.5F).lineSpacing(10F).build())
							                .backgroundColor(Color.WHITE)
							                .textColor(Color.BLACK)
							                .font(fontMarathi).fontSize(10)				              
							                .horizontalAlignment(CENTER)
							                .height(20F)
							                .build();
						         
						         custDetailsTableBuilder.addRow(custInfoRow);
						         
						         currentY = currentY - 20;
					        	 
					        	
					         }
			        		 
			        		 if(pageCount==1 || custDetailsTableBuilder != null)
			        		 {

				        	 custDetailsTable = custDetailsTableBuilder.build();
				        	 TableDrawer.builder()
				                .contentStream(contentStream)
				                .table(custDetailsTable)
				                .startX(PADDING20)
				                .startY(startY-65)
				                .build()
				                .draw();
			        		 }

					         	contentStream.close();
							 	document.save(path+"/employee-list.pdf");
						        document.close();
						        
						        

								response.setHeader("Content-disposition", "inline; filename=employee-list.pdf");
								response.setContentType("application/pdf");
								FileInputStream fileInputStream = new FileInputStream(path+"/employee-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) 
				{

					e.printStackTrace();
					addActionError(e.getErrorCode()+" || "+e.getMessage() +" || 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;
	}
	
	public void setSession(Map<String, Object> map) {  
	    sessionMap=(SessionMap<String, Object>)map;  
	}
    
}

