package com.reallinkbilling.add;

import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;

import org.apache.struts2.dispatcher.SessionMap;
import org.apache.struts2.interceptor.SessionAware;

import com.opensymphony.xwork2.ActionSupport;
import com.reallinkbilling.db.GetDBConnection;
import com.reallinkbilling.resource.CheckAlreadyAvailable;

public class CalculateAndAddEmployeeSalaryDetails extends ActionSupport implements SessionAware {

	/**
	 * 
	 */
	private static final long serialVersionUID = 7942440388806883989L;
	private String employeeIdName;
	private String fromDate;
	private String toDate;
	private SessionMap<String,Object> sessionMap;
	private Integer noOfDaysAbsentDays;
	private Integer noOfOverTime;
	private Integer noOfHalfDays;
	private Integer noOfDaysInMonth;
	private Integer noOfFullDays;
	private Float additionalDeduction;
	private Float additionalPayment;
	private String totalSalary;
	private String comments;
	private String addSideBarJs;
	
	public String execute() {
		 
		String result = "login";
	      if(this.getSessionMap()==null || this.getSessionMap().get("login")==null){ 
	        	addActionMessage("Please Logout and Login again !");
	        	result = "error";
	        }  
	        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
				{
					
					String user = (String)this.getSessionMap().get("userFullName");
					String shortName = "";
					
					try
					{
						shortName = user.split(" ")[0];
					}catch(Exception e)
					{
						shortName = user;
					}
					
					
					connection = GetDBConnection.getDBConnection(db);
					
					sql = "SELECT "
							+ "entry_id "
							+ "FROM "
							+ "shop_employee_salary_calculation_details "
							+ "ORDER BY "
							+ "entry_id "
							+ "DESC LIMIT 1;";
					
				
				preparedStatement = connection.prepareStatement(sql);
				resultSet = preparedStatement.executeQuery();
				
				int entryId = 1;
				
				if(resultSet.next())
				{
					if(!(resultSet.getString(1) == null))
					{
						entryId =resultSet.getInt(1);
						
						
						entryId = entryId+1;
					}
					else
					{
						entryId =1;
					}
				}
					
				if(resultSet != null)
				{
					resultSet.close();
					resultSet = null;
				}
				if(preparedStatement != null)
				{
					preparedStatement.close();
					preparedStatement = null;
				}
				
				Date d = new Date();
	        	SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy");
	        	
	    		
				java.util.Date date = new java.util.Date();
      	      long t = date.getTime();	        	     
      	      java.sql.Time time = new java.sql.Time(t);
				
					String [] employeeDetails = this.getEmployeeIdName().split("-");
					
					String employeeId = employeeDetails[0];
					String employeeName = employeeDetails[1];
					
					sql = "INSERT "
							+ "INTO "
							+ "shop_employee_salary_calculation_details "
							+ "("
							+ "entry_id,"
							+ "shop_id,"
							+ "shop_code,"
							+ "entry_date,"
							+ "entry_time,"
							+ "salary_from_date,"
							+ "salary_to_date,"
							+ "employee_id,"
							+ "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,"
							+ "entry_by) "
							+ "VALUES "
							+ "(?,?,?,STR_TO_DATE(?,'%d-%m-%Y'),?,STR_TO_DATE(?,'%d-%m-%Y'),STR_TO_DATE(?,'%d-%m-%Y'),?,?,?,?,?,?,?,?,?,?,?,?)";
					
					preparedStatement = connection.prepareStatement(sql);
					
					preparedStatement.setInt(1, entryId);
					preparedStatement.setString(2, shopId);
					preparedStatement.setString(3, shopCode);
					preparedStatement.setString(4, dateFormat.format(d));
					preparedStatement.setTime(5, time);
					preparedStatement.setString(6, this.getFromDate());
					preparedStatement.setString(7, this.getToDate());
					preparedStatement.setString(8, employeeId);
					preparedStatement.setString(9, employeeName);
					preparedStatement.setInt(10, this.getNoOfDaysInMonth());
					preparedStatement.setInt(11, this.getNoOfDaysAbsentDays());
					preparedStatement.setInt(12, this.getNoOfOverTime());
					preparedStatement.setInt(13, this.getNoOfHalfDays());
					preparedStatement.setInt(14, this.getNoOfFullDays());
					preparedStatement.setFloat(15, this.getAdditionalDeduction());
					preparedStatement.setFloat(16, this.getAdditionalPayment());
					preparedStatement.setString(17, this.getTotalSalary());
					preparedStatement.setString(18, this.getComments() + " SALARY CALCULATED FOR "+this.getFromDate()+" TO "+this.getToDate());
					preparedStatement.setString(19, shortName);
					
					int rowCount = preparedStatement.executeUpdate();
					
					if(rowCount > 0)
					{
						result = SUCCESS;
						
						this.setEmployeeIdName("");
						this.setNoOfDaysInMonth(0);
						this.setNoOfDaysAbsentDays(0);
						this.setNoOfFullDays(0);
						this.setNoOfHalfDays(0);
						this.setNoOfOverTime(0);
						this.setAdditionalDeduction(0f);
						this.setAdditionalPayment(0f);
						this.setTotalSalary("0");
						
						addActionMessage("Salary details added successfully!");
					}
					else
					{
						result = ERROR;
						addActionError("details not added! Please try again!");
						
					}
					
					
				}catch (SQLException e) {
					e.printStackTrace();
					result = ERROR;
					addActionError("details not added! Please try again!");
				} catch (IOException e) {
					result = ERROR;
					addActionError("details not added! Please try again!");
				}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) {}
					}
				}
	        }
	      
	      return result;
	}
	@Override
	public void validate() {
		
		if(this.getFromDate() == null || this.getFromDate().equals(""))
		{
			addActionError("Please select from date!");
		}
		
		if(!hasActionErrors()){
			if(this.getToDate() == null || this.getToDate().equals(""))
			{
				addActionError("Please select to date!");
			}
		}
		if(!hasActionErrors())
		{
			if(this.getEmployeeIdName() == null || this.getEmployeeIdName().equals(""))
			{
				addActionError("Please provide employee details!");
			}
		}
		
		if(!hasActionErrors())
		{
			if(this.getTotalSalary() == null || this.getTotalSalary().equals(""))
			{
				addActionError("Please provide all other details!");
			}
		}
		
		
		if(!hasActionErrors())
		{
			String isEntryAdded = "false";
			
			String [] result = new String[2];
			String condition = "AND salary_from_date = STR_TO_DATE('"+this.getFromDate()+"','%d-%m-%Y')";
			
			result = new CheckAlreadyAvailable().checkAvaibility("shop_employee_salary_calculation_details", "employee_id", condition , this.getEmployeeIdName().split("-")[0], this.getSessionMap());
			
			isEntryAdded = result[0];
			
			if(isEntryAdded.equals("true"))
			{
				addActionError("Salary details already added for this employee for this dates!");
			}				
			
		}
		
		this.setAddSideBarJs("FALSE");
	}
	

	


	public String getEmployeeIdName() {
		return employeeIdName;
	}
	public void setEmployeeIdName(String employeeIdName) {
		this.employeeIdName = employeeIdName;
	}
	public Integer getNoOfDaysAbsentDays() {
		return noOfDaysAbsentDays;
	}


	public void setNoOfDaysAbsentDays(Integer noOfDaysAbsentDays) {
		this.noOfDaysAbsentDays = noOfDaysAbsentDays;
	}


	public Integer getNoOfOverTime() {
		return noOfOverTime;
	}


	public void setNoOfOverTime(Integer noOfOverTime) {
		this.noOfOverTime = noOfOverTime;
	}


	public Integer getNoOfHalfDays() {
		return noOfHalfDays;
	}


	public void setNoOfHalfDays(Integer noOfHalfDays) {
		this.noOfHalfDays = noOfHalfDays;
	}


	public Integer getNoOfDaysInMonth() {
		return noOfDaysInMonth;
	}


	public void setNoOfDaysInMonth(Integer noOfDaysInMonth) {
		this.noOfDaysInMonth = noOfDaysInMonth;
	}


	public Integer getNoOfFullDays() {
		return noOfFullDays;
	}


	public void setNoOfFullDays(Integer noOfFullDays) {
		this.noOfFullDays = noOfFullDays;
	}


	public Float getAdditionalDeduction() {
		return additionalDeduction;
	}


	public void setAdditionalDeduction(Float additionalDeduction) {
		this.additionalDeduction = additionalDeduction;
	}


	public Float getAdditionalPayment() {
		return additionalPayment;
	}


	public void setAdditionalPayment(Float additionalPayment) {
		this.additionalPayment = additionalPayment;
	}


	public String getTotalSalary() {
		return totalSalary;
	}


	public void setTotalSalary(String totalSalary) {
		this.totalSalary = totalSalary;
	}


	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 static long getSerialversionuid() {
		return serialVersionUID;
	}


	public String getComments() {
		return comments;
	}


	public void setComments(String comments) {
		this.comments = comments;
	}


	public String getAddSideBarJs() {
		return addSideBarJs;
	}
	public void setAddSideBarJs(String addSideBarJs) {
		this.addSideBarJs = addSideBarJs;
	}
	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;  
	}
	
}
