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.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
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.cipher.EncryptionDecryption;
import com.reallinkbilling.db.GetDBConnection;

public class DownloadEmployeeSalarySlip extends ActionSupport implements SessionAware{

	
	
	/**
	 * 
	 */
	private static final long serialVersionUID = 3036323997622786073L;
	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 PADDING20 = 20f;
    private static final float PADDING30 = 30f;
    private SessionMap<String,Object> sessionMap;
	
	private HttpSession session;
	private String entryId;
	private String fromDate;
	private String toDate;
	private String laborName;
	private String noOfDaysInMonth;
	private String noOfAbsentDays;
	private String noOfOverTime;
	private String noOfHalfDays;
	private String noOfFullDaysPresent;
	private String additionalDeductionAmt;
	private String additionalPaymentAmt;
	private String totalSalary;
	private String comments;
	private String key;
    
    
   public void download() throws ParseException
	
    {
		
		 
	        if(this.getSessionMap()==null || this.getSessionMap().get("login")==null){ 
	        	
	        }  
	        else{
	        	
	        	response = ServletActionContext.getResponse();
				request = ServletActionContext.getRequest();
				
				String shopId = (String) this.getSessionMap().get("shopId");
	    		String shopCode = (String) this.getSessionMap().get("shopCode");
	    		
				Connection connection = null;
				PreparedStatement preparedStatement= null;
				ResultSet resultSet = null;
			
				String entryId  = EncryptionDecryption.decrypt(this.getEntryId());
    				
				String sql = "";
				String db = (String)  this.getSessionMap().get("db");
				
				try
				{
					connection = GetDBConnection.getDBConnection(db);
					
					sql = "SELECT "
							+ "entry_id,"
							+ "DATE_FORMAT(salary_from_date,'%d-%M-%Y'),"
							+ "DATE_FORMAT(salary_to_date,'%d-%M-%Y'),"
							+ "employee_name,"
							+ "no_of_day_in_month,"
							+ "no_of_absent_days,"
							+ "no_of_over_time,"
							+ "no_of_half_days,"
							+ "no_of_full_days_present,"
							+ "additional_deduction_amount,"
							+ "additional_payment_amount,"
							+ "total_calculated_salary_amount,"
							+ "comments "
							+ "FROM "
							+ "shop_employee_salary_calculation_details "
							+ "WHERE "
							+ "entry_id = ? "
							+ "AND "
							+ "employee_id = ? "
							+ "AND "
							+ "shop_id = ? "
							+ "AND "
							+ "shop_code = ? ";
					
					preparedStatement = connection.prepareStatement(sql);
    				preparedStatement.setString(1, entryId);
    				preparedStatement.setString(2, EncryptionDecryption.decrypt(this.getKey()));
    				preparedStatement.setString(3, shopId);
    				preparedStatement.setString(4, shopCode);
    				
    				resultSet = preparedStatement.executeQuery();
    				
    				if(resultSet.next())
    				{
    					this.setFromDate(resultSet.getString(2));
    					this.setToDate(resultSet.getString(3));
    					this.setLaborName(resultSet.getString(4));
    					this.setNoOfDaysInMonth(resultSet.getString(5));
    					this.setNoOfAbsentDays(resultSet.getString(6));
    					this.setNoOfOverTime(resultSet.getString(7));    				
    					this.setNoOfHalfDays(resultSet.getString(8));
    					this.setNoOfFullDaysPresent(resultSet.getString(9));
    					this.setAdditionalDeductionAmt(resultSet.getString(10));
    					this.setAdditionalPaymentAmt(resultSet.getString(11));
    					this.setTotalSalary(resultSet.getString(12));
    					this.setComments(resultSet.getString(13));
    					
    					
    				}
    				else
    				{
    				
    					addActionError("SALARY details not found!");
    				}
	       			
	       		 String path=	request.getSession().getServletContext().getRealPath("/images/");
	    			PDDocument document = new PDDocument(); 
					PDPage page = null;
					
					SimpleDateFormat sdf = new SimpleDateFormat("dd-MMM-Y");
					Date date = new Date();
					
					sdf.format(date); 
					page = new PDPage(new PDRectangle(595.2756f,420.9449f));
					
					 File fontFile  =  new File( request.getSession().getServletContext().getRealPath("/fonts/Nirmala.ttf"));
					 TrueTypeFont ttf1 = new TTFParser().parse(fontFile);
					 PDFont fontMarathi = PDType0Font.load(document, ttf1, true);
					
				        document.addPage(page);
				         PDPageContentStream contentStream = new PDPageContentStream(document, page);
				         int pageCount = 1;
			    			 
				         Table header;
			    			
			    			
			    			  TableBuilder tableHeaderBuilder = Table.builder()
						                .addColumnsOfWidth(595)				                
						                .font(HELVETICA)
						                .borderColor(Color.BLACK)
						                .horizontalAlignment(CENTER);
					         
					          Row headerName = 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(18)				              
						                .horizontalAlignment(CENTER)
						                .build();
					          
					          
					         
					          
					          Row info1 = Row.builder()
						                .add(TextCell.builder().text("Salary Slip for :"+this.getFromDate()+" To "+this.getToDate()).borderWidthBottom(0.0F).horizontalAlignment(CENTER).build())				               
						                .backgroundColor(WHITE)
						                .textColor(Color.BLACK)
						                .font(PDType1Font.HELVETICA_BOLD).fontSize(10)
						                .horizontalAlignment(CENTER)
						                .build();
					          
					      
					          tableHeaderBuilder.addRow(headerName);
					
					          tableHeaderBuilder.addRow(info1);
					       
					          header = tableHeaderBuilder.build();
					          
					          
					          
					          
					          
					          Table laborDetails ;
					          
					          TableBuilder laborDetailsBuilder = Table.builder()
						                .addColumnsOfWidth(100,280)				                
						                .font(HELVETICA)
						                .borderWidth(0.5F)
						                .borderColor(Color.BLACK)
						                .horizontalAlignment(CENTER);
					          
					          
					          Row laborDetailsRow1 = Row.builder()
					        		  	.add(TextCell.builder().text("Name:").horizontalAlignment(LEFT).borderWidth(0.0F).lineSpacing(0.1F).build())				                
						                .add(TextCell.builder().text(this.getLaborName()).horizontalAlignment(LEFT).borderWidth(0.0F).lineSpacing(1F).build())
						                .backgroundColor(Color.WHITE)
						                .textColor(Color.BLACK)
						                .font(PDType1Font.HELVETICA_BOLD).fontSize(10)				              
						                .horizontalAlignment(CENTER)
						                .height(25F)	
						                .build();
					          
					          
					          laborDetailsBuilder.addRow(laborDetailsRow1);
					          
					          laborDetails = laborDetailsBuilder.build();
					          
					          float startY = page.getMediaBox().getHeight() - PADDING20;
					          float currentY = startY;
					          TableDrawer.builder()
				                .contentStream(contentStream)
				                .table(header)
				                .startX(0)
				                .startY(startY)
				                .build()
				                .draw();

				        			
					          Table salarySlipDetails ;
					          
					          TableBuilder salarySlipDetailsBuilder = Table.builder()
						                .addColumnsOfWidth(135,135,135,135)				                
						                .font(HELVETICA)
						                .borderWidth(0.5F)
						                .borderColor(Color.BLACK)
						                .horizontalAlignment(CENTER);
				       		
				        		
				        		Row row1 = Row.builder()
					        			  	.add(TextCell.builder().text("No Of Days In Month").horizontalAlignment(LEFT).borderWidth(0.5F).lineSpacing(1F).build())				                
					        				.add(TextCell.builder().text(this.getNoOfDaysInMonth()).horizontalAlignment(RIGHT).borderWidth(0.5F).lineSpacing(1F).build())				                
					        			  	.add(TextCell.builder().text("No Of Full Present Days").horizontalAlignment(RIGHT).borderWidth(0.5F).lineSpacing(1F).build())				                
					        			  	.add(TextCell.builder().text(this.getNoOfFullDaysPresent()).horizontalAlignment(RIGHT).borderWidth(0.5F).lineSpacing(1F).build())				                
					        			   	.backgroundColor(Color.WHITE)
							                .textColor(Color.BLACK)
							                .font(PDType1Font.HELVETICA)
							                .fontSize(10)				              
							                .horizontalAlignment(CENTER)
							                .height(25F)					                
							                .build();
				        		
				        		Row row2 = Row.builder()
				        			  	.add(TextCell.builder().text("No Of Over Time In Month").horizontalAlignment(LEFT).borderWidth(0.5F).lineSpacing(1F).build())				                
				        				.add(TextCell.builder().text(this.getNoOfOverTime()).horizontalAlignment(RIGHT).borderWidth(0.5F).lineSpacing(1F).build())				                
				        			  	.add(TextCell.builder().text("No Of Absent Days").horizontalAlignment(RIGHT).borderWidth(0.5F).lineSpacing(1F).build())				                
				        			  	.add(TextCell.builder().text(this.getNoOfAbsentDays()).horizontalAlignment(RIGHT).borderWidth(0.5F).lineSpacing(1F).build())				                
				        			   	.backgroundColor(Color.WHITE)
						                .textColor(Color.BLACK)
						                .font(PDType1Font.HELVETICA)
						                .fontSize(10)				              
						                .horizontalAlignment(CENTER)
						                .height(25F)					                
						                .build();
				        		Row row3 = Row.builder()
				        			  	.add(TextCell.builder().text("No Of Half Days In Month").horizontalAlignment(LEFT).borderWidth(0.5F).lineSpacing(1F).build())				                
				        				.add(TextCell.builder().text(this.getNoOfHalfDays()).horizontalAlignment(RIGHT).borderWidth(0.5F).lineSpacing(1F).build())				                
				        			  	.add(TextCell.builder().text("").horizontalAlignment(RIGHT).borderWidth(0.5F).lineSpacing(1F).build())				                
				        			  	.add(TextCell.builder().text("").horizontalAlignment(RIGHT).borderWidth(0.5F).lineSpacing(1F).build())				                
				        			   	.backgroundColor(Color.WHITE)
						                .textColor(Color.BLACK)
						                .font(PDType1Font.HELVETICA)
						                .fontSize(10)				              
						                .horizontalAlignment(CENTER)
						                .height(25F)					                
						                .build();
				        		
				        		Row row4 = Row.builder()
				        			  	.add(TextCell.builder().text("Additional Deduction").horizontalAlignment(LEFT).borderWidth(0.5F).lineSpacing(1F).build())				                
				        				.add(TextCell.builder().text(this.getAdditionalDeductionAmt()).horizontalAlignment(RIGHT).borderWidth(0.5F).lineSpacing(1F).build())				                
				        			  	.add(TextCell.builder().text("Additional Payment").horizontalAlignment(RIGHT).borderWidth(0.5F).lineSpacing(1F).build())				                
				        			  	.add(TextCell.builder().text(this.getAdditionalPaymentAmt()).horizontalAlignment(RIGHT).borderWidth(0.5F).lineSpacing(1F).build())				                
				        			   	.backgroundColor(Color.WHITE)
						                .textColor(Color.BLACK)
						                .font(PDType1Font.HELVETICA)
						                .fontSize(10)				              
						                .horizontalAlignment(CENTER)
						                .height(25F)					                
						                .build();
				        		
				        		Row comments = Row.builder()
				        			  	.add(TextCell.builder().text("Comments").horizontalAlignment(LEFT).borderWidth(0.5F).lineSpacing(1F).build())				                
				        				.add(TextCell.builder().text(this.getComments()).colSpan(3).horizontalAlignment(LEFT).borderWidth(0.5F).lineSpacing(1F).build())				                
				        			   	.backgroundColor(Color.WHITE)
						                .textColor(Color.BLACK)
						                .font(fontMarathi)
						                .fontSize(10)				              
						                .horizontalAlignment(CENTER)
						                .height(25F)					                
						                .build();
				        		
				        		Row netSalary = Row.builder()
				        			  	.add(TextCell.builder().text("Net Salary").colSpan(3).horizontalAlignment(RIGHT).borderWidth(0.5F).lineSpacing(1F).build())				                
				        				.add(TextCell.builder().text(this.getTotalSalary()).horizontalAlignment(RIGHT).borderWidth(0.5F).lineSpacing(1F).build())				                
				        			   	.backgroundColor(Color.WHITE)
						                .textColor(Color.BLACK)
						                .font(PDType1Font.HELVETICA_BOLD)
						                .fontSize(12)				              
						                .horizontalAlignment(CENTER)
						                .height(25F)					                
						                .build();
					        	  
				        		salarySlipDetailsBuilder.addRow(row1);
				        		salarySlipDetailsBuilder.addRow(row2);
				        		salarySlipDetailsBuilder.addRow(row3);
				        		salarySlipDetailsBuilder.addRow(row4);
				        		salarySlipDetailsBuilder.addRow(comments);
				        		salarySlipDetailsBuilder.addRow(netSalary);
					        	
				        	  
				        		salarySlipDetails = salarySlipDetailsBuilder.build();
				        	  
				        		
				        		 TableDrawer.builder()
					                .contentStream(contentStream)
					                .table(laborDetails)
					                .startX(PADDING20)
					                .startY(startY-90)
					                .build()
					                .draw();

				        		 
				        	  TableDrawer.builder()
				                .contentStream(contentStream)
				                .table(salarySlipDetails)
				                .startX(PADDING20)
				                .startY(startY-120)
				                .build()
				                .draw();
					
					          
					          
					          contentStream.close();
						        
						       // System.out.println(path);
										
						        
						        document.save(path+"/employee-salary-slip.pdf");
						        document.close();
						        
						        response.setHeader("Content-disposition", "inline; filename=employee-salary-slip.pdf");
								response.setContentType("application/pdf");
								FileInputStream fileInputStream = new FileInputStream(path+"/employee-salary-slip.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();
	    			
	    		} catch (IOException 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 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 HttpSession getSession() {
	return session;
}



public void setSession(HttpSession session) {
	this.session = session;
}




public String getEntryId() {
	return entryId;
}



public void setEntryId(String entryId) {
	this.entryId = entryId;
}



public String getLaborName() {
	return laborName;
}



public void setLaborName(String laborName) {
	this.laborName = laborName;
}




public String getFromDate() {
	return fromDate;
}



public void setFromDate(String fromDate) {
	this.fromDate = fromDate;
}



public String getToDate() {
	return toDate;
}



public void setToDate(String toDate) {
	this.toDate = toDate;
}



public String getNoOfDaysInMonth() {
	return noOfDaysInMonth;
}



public void setNoOfDaysInMonth(String noOfDaysInMonth) {
	this.noOfDaysInMonth = noOfDaysInMonth;
}



public String getNoOfAbsentDays() {
	return noOfAbsentDays;
}



public void setNoOfAbsentDays(String noOfAbsentDays) {
	this.noOfAbsentDays = noOfAbsentDays;
}



public String getNoOfOverTime() {
	return noOfOverTime;
}



public void setNoOfOverTime(String noOfOverTime) {
	this.noOfOverTime = noOfOverTime;
}



public String getNoOfHalfDays() {
	return noOfHalfDays;
}



public void setNoOfHalfDays(String noOfHalfDays) {
	this.noOfHalfDays = noOfHalfDays;
}



public String getNoOfFullDaysPresent() {
	return noOfFullDaysPresent;
}



public void setNoOfFullDaysPresent(String noOfFullDaysPresent) {
	this.noOfFullDaysPresent = noOfFullDaysPresent;
}



public String getAdditionalDeductionAmt() {
	return additionalDeductionAmt;
}



public void setAdditionalDeductionAmt(String additionalDeductionAmt) {
	this.additionalDeductionAmt = additionalDeductionAmt;
}



public String getAdditionalPaymentAmt() {
	return additionalPaymentAmt;
}



public void setAdditionalPaymentAmt(String additionalPaymentAmt) {
	this.additionalPaymentAmt = additionalPaymentAmt;
}



public String getTotalSalary() {
	return totalSalary;
}



public void setTotalSalary(String totalSalary) {
	this.totalSalary = totalSalary;
}



public String getComments() {
	return comments;
}



public void setComments(String comments) {
	this.comments = comments;
}



public static long getSerialversionuid() {
	return serialVersionUID;
}



public void setSession(Map<String, Object> map) {  
    sessionMap=(SessionMap<String, Object>)map;  
}


public SessionMap<String, Object> getSessionMap() {
	return sessionMap;
}

public void setSessionMap(SessionMap<String, Object> sessionMap) {
	this.sessionMap = sessionMap;
}



public String getKey() {
	return key;
}



public void setKey(String key) {
	this.key = key;
}

}
