package com.reallinkbilling.add;

import java.io.File;
import java.io.FileInputStream;
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.LinkedHashMap;
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;
import com.reallinkbilling.resource.GetNewIdForNewEntry;

public class AddNewEmployeeDetails extends ActionSupport implements SessionAware{

	/**
	 * 
	 */
	private static final long serialVersionUID = 7265344080433556418L;
	private SessionMap<String,Object> sessionMap;
	private String employeeName;
	private String employeeMobileNumber;
	private String address;
	private String birthDate;
	private String employeeId;
	private File employeeImage;
	private HashMap<String,String> designationList = new LinkedHashMap<String,String>();
	private String employeePANNumber;
	private String employeeAADHARNumber;
	private String employeeBankName;
	private String employeeAccNumber;
	private String employeeBankBranch;
	private String employeeIFSCCode;
	private String designation;
	private String addSideBarJs;

	
	public String execute() throws IOException{
		 
		String result = "login";
		
		  if(this.getSessionMap()==null || this.getSessionMap().get("login")==null){ 
	        	addActionMessage("Please Logout and Login again !");
	        	result = "login";
	        }  
	        else{
	        	
	        	Connection connection = null;
				PreparedStatement preparedStatement= null;
				ResultSet resultSet = null;

				String tradeCompId = (String) this.getSessionMap().get("shopId");
		    	String tradeCompCode = (String) this.getSessionMap().get("shopCode");
		    		
				String sql = "";
				String db = (String) this.getSessionMap().get("db");
				FileInputStream fis  = null;
				if(this.getEmployeeImage() != null)
				{
				 fis =  new FileInputStream(this.getEmployeeImage());
				}
			
					try
					{
						connection = GetDBConnection.getDBConnection(db);
						
						int newEmployeeId = GetNewIdForNewEntry.getNewIdForNewEntry
								("shop_employee_master", "employee_id", this.getSessionMap(), connection);
						
						int rowAdded = 0;
						
						if(this.getEmployeeImage() != null)
						{
							sql = "INSERT INTO "
									+ "shop_employee_master "
									+ "("
									+ "employee_id,"
									+ "shop_id,"
									+ "shop_code,"
									+ "employee_name,"
									+ "employee_mobile_number,"
									+ "employee_address,"
									+ "employee_birth_date,"
									+ "employee_image,"
									+ "employee_aadhar_number,"
									+ "employee_pan_number,"
									+ "employee_bank_name,"
									+ "employee_bank_acc_number,"
									+ "employee_bank_ifsc_code,"
									+ "employee_bank_branch,"
									+ "employee_designation) "
									+ "VALUES "
									+ "(?,?,?,?,?,?,STR_TO_DATE(?,'%d-%m-%Y'),?,?,?,?,?,?,?,?)";
							
							preparedStatement = connection.prepareStatement(sql);
							
							preparedStatement.setInt(1, newEmployeeId);
							preparedStatement.setString(2, tradeCompId);
							preparedStatement.setString(3, tradeCompCode);
							preparedStatement.setString(4, this.getEmployeeName().trim().toUpperCase());
							preparedStatement.setString(5, this.getEmployeeMobileNumber().trim());
							preparedStatement.setString(6, this.getAddress().trim().toUpperCase());
							preparedStatement.setString(7, this.getBirthDate());
							preparedStatement.setBinaryStream(8, fis,(int)this.getEmployeeImage().length() );
							preparedStatement.setString(9, this.getEmployeeAADHARNumber().trim().toUpperCase());
							preparedStatement.setString(10, this.getEmployeePANNumber().trim().toUpperCase());
							preparedStatement.setString(11, this.getEmployeeBankName().trim().toUpperCase());
							preparedStatement.setString(12, this.getEmployeeAccNumber().trim().toUpperCase());
							preparedStatement.setString(13, this.getEmployeeIFSCCode().trim().toUpperCase());
							preparedStatement.setString(14, this.getEmployeeBankBranch().trim().toUpperCase());
							preparedStatement.setString(15, this.getDesignation());
							
							rowAdded = preparedStatement.executeUpdate();
						}
						else if(this.getEmployeeImage() == null)
						{	
								sql = "INSERT INTO "
									+ "shop_employee_master "
									+ "("
									+ "employee_id,"
									+ "shop_id,"
									+ "shop_code,"
									+ "employee_name,"
									+ "employee_mobile_number,"
									+ "employee_address,"
									+ "employee_birth_date,"
									+ "employee_aadhar_number,"
									+ "employee_pan_number,"
									+ "employee_bank_name,"
									+ "employee_bank_acc_number,"
									+ "employee_bank_ifsc_code,"
									+ "employee_bank_branch,"
									+ "employee_designation) "
									+ "VALUES "
									+ "(?,?,?,?,?,?,STR_TO_DATE(?,'%d-%m-%Y'),?,?,?,?,?,?,?)";
							
							preparedStatement = connection.prepareStatement(sql);
							
							preparedStatement.setInt(1, newEmployeeId);
							preparedStatement.setString(2, tradeCompId);
							preparedStatement.setString(3, tradeCompCode);
							preparedStatement.setString(4, this.getEmployeeName().trim().toUpperCase());
							preparedStatement.setString(5, this.getEmployeeMobileNumber().trim());
							preparedStatement.setString(6, this.getAddress().trim().toUpperCase());
							preparedStatement.setString(7, this.getBirthDate());
							preparedStatement.setString(8, this.getEmployeeAADHARNumber().trim().toUpperCase());
							preparedStatement.setString(9, this.getEmployeePANNumber().trim().toUpperCase());
							preparedStatement.setString(10, this.getEmployeeBankName().trim().toUpperCase());
							preparedStatement.setString(11, this.getEmployeeAccNumber().trim().toUpperCase());
							preparedStatement.setString(12, this.getEmployeeIFSCCode().trim().toUpperCase());
							preparedStatement.setString(13, this.getEmployeeBankBranch().trim().toUpperCase());
							preparedStatement.setString(14, this.getDesignation());
							
							rowAdded = preparedStatement.executeUpdate();
						}
						
						if(rowAdded > 0)
						{
							this.setEmployeeId(""+newEmployeeId);
							addActionMessage("Employee details added successfully!");
							result = SUCCESS;
						}
						else
						{
							addActionError("Employee details not added ! Please try again!");
							result =ERROR;
							
						}
					}catch (SQLException e) {
						//e.printStackTrace();
						result =ERROR;				
						addActionError(e.getErrorCode()+" || "+e.getMessage() +" || Employee details not added !");
					
					} catch (IOException e) {
						//e.printStackTrace();
						result =ERROR;			
						addActionError(e.getMessage()+" || "+e.getCause()+" || Employee details not added !");
					
					}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) {}
						}
						
					}
	        	
	        	
	        	if(fis != null)
	        	{
	        		fis.close();
	        		fis = null;
	        	}
	        	
	        }
	        return result;
	}
		
	@SuppressWarnings("unchecked")
	@Override
	public void validate() {
		
	  	this.setDesignationList((HashMap<String, String>) this.getSessionMap().get("designationlist"));
    	this.setAddSideBarJs("FALSE");
   	   
    	this.getDesignationList().put("", "--- SELECT DESIGNATION ---");
		
		if(this.getEmployeeName() == null || this.getEmployeeName().equals(""))
		{
			addActionError("Please provide Employee name!");
		}
		
		if(!hasActionErrors())
		{
			if(this.getEmployeeMobileNumber() == null || this.getEmployeeMobileNumber().equals(""))
			{
				addActionError("Please provide Employee mobile number!");
			}else if(this.getEmployeeMobileNumber().length() != 10)
			{
				addActionError("Please provide Employee mobile number!");
			}
		}
		
		
		if(!hasActionErrors())
		{
			if(this.getAddress() == null || this.getAddress().equals(""))
			{
				addActionError("Please provide correct address!");
			}
				
		}
		
		if(!hasActionErrors())
		{
			if(this.getBirthDate() == null || this.getBirthDate().equals(""))
			{
				addActionError("Please select Employee birth date!");
			}
		}
		
		
		if(!hasActionErrors())
		{
			String isCustomerAdded = "false";
			
			String [] result = new String[2];
			String condition  = "NA";
			result = new CheckAlreadyAvailable().checkAvaibility("shop_employee_master", "employee_mobile_number", condition,this.getEmployeeMobileNumber(), this.getSessionMap());
			
			isCustomerAdded = result[0];
			
			if(isCustomerAdded.equals("true"))
			{
				addActionError("Employee is already added with same name OR mobile number!");
			}				
			
		}
		
		if(!hasActionErrors())
		{
			if(this.getEmployeeAADHARNumber() == null || this.getEmployeeAADHARNumber().equals(""))
			{
				addActionError("Please provide employee AADHAR number!");
			}
		}
		
		if(!hasActionErrors())
		{
			if(this.getEmployeePANNumber() == null || this.getEmployeePANNumber().equals(""))
			{
				addActionError("Please provide employee PAN number!");
			}
		}
		if(!hasActionErrors())
		{
			if(this.getEmployeeBankName() == null || this.getEmployeePANNumber().equals(""))
			{
				addActionError("Please provide employee Bank Name!");
			}
		}
		
		if(!hasActionErrors())
		{
			if(this.getEmployeeIFSCCode() == null || this.getEmployeeIFSCCode().equals(""))
			{
				addActionError("Please provide bank IFSC code!");
			}
		}
		
		if(!hasActionErrors())
		{
			if(this.getEmployeeBankBranch() == null || this.getEmployeeBankBranch().equals(""))
			{
				addActionError("Please provide branch name!");
			}
		}
		if(!hasActionErrors())
		{
			if(this.getDesignation() == null || this.getDesignation().equals(""))
			{
				addActionError("Please select designation of employee!");
			}
		}
		
	}


	

	public String getEmployeeName() {
		return employeeName;
	}

	public void setEmployeeName(String employeeName) {
		this.employeeName = employeeName;
	}

	public String getEmployeeMobileNumber() {
		return employeeMobileNumber;
	}

	public void setEmployeeMobileNumber(String employeeMobileNumber) {
		this.employeeMobileNumber = employeeMobileNumber;
	}

	public String getEmployeeId() {
		return employeeId;
	}

	public void setEmployeeId(String employeeId) {
		this.employeeId = employeeId;
	}

	public File getEmployeeImage() {
		return employeeImage;
	}

	public void setEmployeeImage(File employeeImage) {
		this.employeeImage = employeeImage;
	}

	public HashMap<String, String> getDesignationList() {
		return designationList;
	}

	public void setDesignationList(HashMap<String, String> designationList) {
		this.designationList = designationList;
	}

	public String getEmployeePANNumber() {
		return employeePANNumber;
	}

	public void setEmployeePANNumber(String employeePANNumber) {
		this.employeePANNumber = employeePANNumber;
	}

	public String getEmployeeAADHARNumber() {
		return employeeAADHARNumber;
	}

	public void setEmployeeAADHARNumber(String employeeAADHARNumber) {
		this.employeeAADHARNumber = employeeAADHARNumber;
	}

	public String getEmployeeBankName() {
		return employeeBankName;
	}

	public void setEmployeeBankName(String employeeBankName) {
		this.employeeBankName = employeeBankName;
	}

	public String getEmployeeAccNumber() {
		return employeeAccNumber;
	}

	public void setEmployeeAccNumber(String employeeAccNumber) {
		this.employeeAccNumber = employeeAccNumber;
	}

	public String getEmployeeBankBranch() {
		return employeeBankBranch;
	}

	public void setEmployeeBankBranch(String employeeBankBranch) {
		this.employeeBankBranch = employeeBankBranch;
	}

	public String getEmployeeIFSCCode() {
		return employeeIFSCCode;
	}

	public void setEmployeeIFSCCode(String employeeIFSCCode) {
		this.employeeIFSCCode = employeeIFSCCode;
	}

	public String getDesignation() {
		return designation;
	}

	public void setDesignation(String designation) {
		this.designation = designation;
	}

	public String getAddress() {
		return address;
	}

	public void setAddress(String address) {
		this.address = address;
	}

	public String getBirthDate() {
		return birthDate;
	}

	public void setBirthDate(String birthDate) {
		this.birthDate = birthDate;
	}

	

	public String getAddSideBarJs() {
		return addSideBarJs;
	}

	public void setAddSideBarJs(String addSideBarJs) {
		this.addSideBarJs = addSideBarJs;
	}
 
	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;
	}


}
