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.util.HashMap;
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 AddEmployeeAbsentyDetails extends ActionSupport implements SessionAware{
	
	
	/**
	 * 
	 */
	private static final long serialVersionUID = -1002181125915309484L;
	private SessionMap<String,Object> sessionMap; 
	
	private String markingDate;
	private String employeeIdName;
	private String typeOfMarking;
	private String details;
	private Map<String,String> typeOfMarkingMap = new HashMap<String,String>();
	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 user = (String) this.getSessionMap().get("userFullName");
				String shortName = "";
				
				try
				{
					shortName = user.split(" ")[0];
				}catch(Exception e)
				{
					shortName = user;
				}
				
				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 [] laborDetails = this.getEmployeeIdName().split("-");
					
					String employeeId = laborDetails[0];
					String employeeName = laborDetails[1];
					String employeeMobile = laborDetails[2];
					
					
					 java.util.Date date = new java.util.Date();
	        	      long t = date.getTime();	        	     
	        	      java.sql.Time time = new java.sql.Time(t);
	        	      
					connection = GetDBConnection.getDBConnection(db);
					connection.setAutoCommit(false);
					

					sql = "SELECT "
							+ "entry_id "
							+ "FROM "
							+ "shop_employee_presenty_details "
							+ "ORDER BY "
							+ "entry_id "
							+ "DESC LIMIT 1;";
					
				
				preparedStatement = connection.prepareStatement(sql);
				resultSet = preparedStatement.executeQuery();
				
				int entryId = 0;
				
				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;
				}
					sql = "INSERT INTO "
							+ "shop_employee_presenty_details "
							+ "(entry_id,"
							+ "shop_id,"
							+ "shop_code,"
							+ "marking_date,"
							+ "marking_time,"
							+ "employee_id,"
							+ "employee_name,"
							+ "type_of_marking,"
							+ "details,"
							+ "entry_by) "
							+ "VALUES "
							+ "(?,?,?,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, this.getMarkingDate());
					preparedStatement.setTime(5, time);
					preparedStatement.setString(6, employeeId);
					preparedStatement.setString(7, employeeName);
					preparedStatement.setString(8, this.getTypeOfMarking());
					preparedStatement.setString(9, this.getDetails());
					preparedStatement.setString(10, shortName);
					
					int k = preparedStatement.executeUpdate();
					
					if(k>0)
					{
						connection.commit();
						result = SUCCESS;
						addActionMessage("Employee absent / half-day / over time details added successfully!");
						
						this.setEmployeeIdName("");
						this.setDetails("");
					}
					else
					{
						result = ERROR;
						addActionError("Details coudn't be added! Please try again!");
					}
					
				}catch (SQLException e) {
					e.printStackTrace();
					try {
						connection.rollback();
					} catch (SQLException e1) {}
					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.getEmployeeIdName() == null || this.getEmployeeIdName().equals(""))
		{
			addActionError("Please provide employee details!");
		}
		else
		{
			try
			{
				int count = this.getEmployeeIdName().split("-").length;
				
				if(count!=3)
				{
					addActionError("Please provide correct employee details!");
				}
			}
			catch (Exception e) {
				addActionError("Please provide correct employee details!");
			}
		}
		
		if(!hasActionErrors())
		{
			String isCustomerAdded = "false";
			
			String [] result = new String[2];
			String condition = "AND marking_date = STR_TO_DATE('"+this.getMarkingDate()+"','%d-%m-%Y')";
			
			result = new CheckAlreadyAvailable()
					.checkAvaibility("shop_employee_presenty_details", "employee_id",
							condition , getEmployeeIdName().split("-")[0], this.getSessionMap());
			
			isCustomerAdded = result[0];
			
			if(isCustomerAdded.equals("true"))
			{
				addActionError("Entry already added for this employee for this date!");
			}				
			
		}
		
		
		this.setAddSideBarJs("FALSE");

    	this.getTypeOfMarkingMap().put("ABSENT", "ABSENT");
    	this.getTypeOfMarkingMap().put("HALFDAY", "HALF-DAY");
    	this.getTypeOfMarkingMap().put("OVERTIME", "OVER-TIME");
		
	}
	
	public String getMarkingDate() {
		return markingDate;
	}


	public void setMarkingDate(String markingDate) {
		this.markingDate = markingDate;
	}



	public String getEmployeeIdName() {
		return employeeIdName;
	}
	public void setEmployeeIdName(String employeeIdName) {
		this.employeeIdName = employeeIdName;
	}
	public String getTypeOfMarking() {
		return typeOfMarking;
	}


	public void setTypeOfMarking(String typeOfMarking) {
		this.typeOfMarking = typeOfMarking;
	}


	public String getDetails() {
		return details;
	}


	public void setDetails(String details) {
		this.details = details;
	}


	public static long getSerialversionuid() {
		return serialVersionUID;
	}


	public Map<String, String> getTypeOfMarkingMap() {
		return typeOfMarkingMap;
	}
	public void setTypeOfMarkingMap(Map<String, String> typeOfMarkingMap) {
		this.typeOfMarkingMap = typeOfMarkingMap;
	}
	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;  
	}

}
