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.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.struts2.ServletActionContext;
import org.apache.struts2.dispatcher.SessionMap;
import org.apache.struts2.interceptor.SessionAware;

import com.opensymphony.xwork2.ActionSupport;
import com.reallinkbilling.cipher.EncryptionDecryption;
import com.reallinkbilling.db.GetDBConnection;
import com.reallinkbilling.utils.GetAccountListForDrCr;
import com.reallinkbilling.utils.GetTypeOfPaymentList;
import com.reallinkbilling.utils.InsertBankAccDrCrEntry;
import com.reallinkbilling.utils.MaintainCloseingBalUtil;

public class AddDailyExpense extends ActionSupport implements SessionAware{

	/**
	 * 
	 */
	private static final long serialVersionUID = 4314678329260462055L;
	
	private String expenseDate;
	private String expenseReason;
	private Float amount;
	private String typeOfPayment;
	private String description;
	private File expenseImage;
	private List<String> paymentTypeList = new ArrayList<String>();
	private HttpSession session;
	public HttpServletRequest request;
	private SessionMap<String,Object> sessionMap;  
	
	private String accountId;
	private Map<String,String> accountList = new LinkedHashMap<String,String>();

	
	public String execute() {
		 
		String result = "login";
		this.setSession(ServletActionContext.getRequest().getSession(false)); 
		
	        if(this.getSession()==null || this.getSession().getAttribute("login")==null){ 
	        	addActionMessage("Please Login First !!!");
	        	result = "login";
	        }  
	        else{
	        	
	        	String shopId = (String) this.getSessionMap().get("shopId");
	    		String shopCode = (String) this.getSessionMap().get("shopCode");
	    		
	        
	        	paymentTypeList.add("CASH");
	        	paymentTypeList.add("UPI");
	        	paymentTypeList.add("RTGS");
	        	paymentTypeList.add("NEFT");
	        	paymentTypeList.add("CHEQUE");
	        
	        	Connection connection = null;
				PreparedStatement preparedStatement= null;
				ResultSet resultSet = null;
				
				String sql = "";
				String db = (String) this.getSession().getAttribute("db");
				FileInputStream fis  = null;
				
				
			
					try
					{
						if(this.getExpenseImage() != null)
						{
						 fis =  new FileInputStream(this.getExpenseImage());
						}
						
					
						
						String fullUserName = (String) this.getSessionMap().get("userFullName");
			        	
			        	String splitUserName [] = new String[5];
			        	
					
						
						String userName = "";
			        	try
			        	{
			        		splitUserName = fullUserName.split(" ");
			        		userName = splitUserName[0];
			        		
			        	}catch(Exception e)
			        	{
			        		userName =fullUserName;
			        	}
						connection = GetDBConnection.getDBConnection(db);
						connection.setAutoCommit(false);
						
						sql = "SELECT "
								+ "entry_id "
								+ "FROM "
								+ "shop_daily_expense_details_master "
								+ "ORDER BY "
								+ "entry_id "
								+ "DESC LIMIT 1;";
						
					
					preparedStatement = connection.prepareStatement(sql);
					resultSet = preparedStatement.executeQuery();
					
					int nextExpenseId = 0;
					
					if(resultSet.next())
					{
						if(!(resultSet.getString(1) == null))
						{
							nextExpenseId = Integer.parseInt(resultSet.getString(1));
							
							
							nextExpenseId = nextExpenseId+1;
						}
						else
						{
							nextExpenseId =1;
						}
					}
						
					if(resultSet != null)
					{
						resultSet.close();
						resultSet = null;
					}
					if(preparedStatement != null)
					{
						preparedStatement.close();
						preparedStatement = null;
					}
					
					java.util.Date date = new java.util.Date();
	        	      long t = date.getTime();	        	     
	        	      java.sql.Time time = new java.sql.Time(t);
	        	      
					
						if(this.getExpenseImage() != null)
						{
						sql = "INSERT INTO "
								+ "shop_daily_expense_details_master "
								+ "("
								+ "entry_id,"
								+ "shop_id,"
								+ "shop_code,"
								+ "expense_date,"
								+ "expense_time,"
								+ "expense_details,"
								+ "exepnse_amount,"
								+ "type_of_payment,"
								+ "expense_image)"
								+ "values "
								+ "(?,?,?,STR_TO_DATE(?, '%d-%m-%Y'),?,?,?,?,?)";
						
						preparedStatement = connection.prepareStatement(sql);
						
						preparedStatement.setString(1, ""+nextExpenseId);
						preparedStatement.setString(2, shopId);
						preparedStatement.setString(3, shopCode);
						preparedStatement.setString(4, this.getExpenseDate());
						preparedStatement.setTime(5, time);
						preparedStatement.setString(6, this.getExpenseReason().trim().toUpperCase());
						preparedStatement.setFloat(7, this.getAmount());
						preparedStatement.setString(8, this.getTypeOfPayment());									
						preparedStatement.setBinaryStream(9, fis,(int)this.getExpenseImage().length() );
						}
						
						else if(this.getExpenseImage() == null)
						{
							sql = "INSERT INTO "
									+ "shop_daily_expense_details_master "
									+ "("
									+ "entry_id,"
									+ "shop_id,"
									+ "shop_code,"
									+ "expense_date,"
									+ "expense_time,"
									+ "expense_details,"
									+ "exepnse_amount,"
									+ "type_of_payment) "
									+ "values "
									+ "(?,?,?,STR_TO_DATE(?, '%d-%m-%Y'),?,?,?,?)";
							
							preparedStatement = connection.prepareStatement(sql);
							
							preparedStatement.setString(1, ""+nextExpenseId);
							preparedStatement.setString(2, shopId);
							preparedStatement.setString(3, shopCode);
							preparedStatement.setString(4, this.getExpenseDate());
							preparedStatement.setTime(5, time);
							preparedStatement.setString(6, this.getExpenseReason().trim().toUpperCase());
							preparedStatement.setFloat(7, this.getAmount());
							preparedStatement.setString(8, this.getTypeOfPayment());									
								
						}
						int i = preparedStatement.executeUpdate();
						
						
						boolean debitEntryAdded = InsertBankAccDrCrEntry.addBankAccDebitEntry(this.getExpenseDate(), this.getAccountId(), this.getAmount(), this.getTypeOfPayment(), this.getSessionMap(),  this.getExpenseReason().trim().toUpperCase());
						boolean isCloseingBalMaintained = MaintainCloseingBalUtil.maintainCloseingBal(this.getAccountId(),"DEBIT", this.getExpenseDate(), this.getAmount(), userName, connection, this.getSessionMap());
						
						
    	        		if(i>0 && debitEntryAdded && isCloseingBalMaintained)	
    	        		{
    	        		
    	        			
    	        			connection.commit();
							result = "success";
							addActionMessage("Expense details added successfully !");
						}
						else
						{
							connection.rollback();
							result = "error";
							addActionError("Error ! Expense details not added ! Please try again !");
						}
						
    	        		
					}catch (SQLException e) {
						try {connection.rollback();} catch (SQLException e1) {}
						result = "error";
						
						addActionError(e.getErrorCode()+" || "+e.getMessage() +" || Expense details not added !");
					} catch (IOException e) {
						
						result = "error";						
						addActionError(e.getMessage()+" || "+e.getCause()+" || Expense 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)
    		        	{
							try {fis.close();}catch (Exception e) {}
    		        	}
						
						
					}
	        	
	        	
	        	
	        	
	        }
	        
	        this.setExpenseReason("");
			this.setExpenseImage(null);
			this.setDescription("");
			this.setAmount(0.0F);
			this.setTypeOfPayment("");
			this.setAccountId("");
	        return result;
	}

	
	public void validate() {
		
		if(this.getExpenseDate().equals("") || this.getExpenseReason().equals("") || this.getAmount() == null)
		{
			addActionError("Please provide details for fields marked with (*) astrick!");
		}
		
		if(!hasActionErrors())
		{
			if(this.getExpenseReason().length() > 99)
			{
				addActionError("Lenght of expense reason is more than 100 characters!");
			}
		}
		
		if(!hasActionErrors())
		{
			if(this.getExpenseImage() != null)
				{
					int sizeOfImage =(int)this.getExpenseImage().length();
					
					if(sizeOfImage >  300000)
					{
						addActionError("Size of image large than 300Kb! Please reduce size of image!");
					}
				}
		}
		
		if(!hasActionErrors())
		{
			if(this.getTypeOfPayment() == null || this.getTypeOfPayment().equals(""))
			{
				addActionError("Please select type of payment!");
			}
		}
		
		if(!hasActionErrors())
		{
			if(this.getAccountId() == null || this.getAccountId().equals(""))
			{
				addActionError("Please select account for debit entry!");
			}
		}
		this.setAccountList(GetAccountListForDrCr.getAccountList(this.getSessionMap())); 
		this.setPaymentTypeList(GetTypeOfPaymentList.getTypeOfPaymentList());
    
	}

	public HttpSession getSession() {
		return session;
	}


	public void setSession(HttpSession session) {
		this.session = session;
	}


	public String getExpenseDate() {
		return expenseDate;
	}


	public void setExpenseDate(String expenseDate) {
		this.expenseDate = expenseDate;
	}


	public String getExpenseReason() {
		return expenseReason;
	}


	public void setExpenseReason(String expenseReason) {
		this.expenseReason = expenseReason;
	}


	public Float getAmount() {
		return amount;
	}


	public void setAmount(Float amount) {
		this.amount = amount;
	}


	public String getTypeOfPayment() {
		return typeOfPayment;
	}


	public void setTypeOfPayment(String typeOfPayment) {
		this.typeOfPayment = typeOfPayment;
	}


	public String getDescription() {
		return description;
	}


	public void setDescription(String description) {
		this.description = description;
	}


	public File getExpenseImage() {
		return expenseImage;
	}


	public void setExpenseImage(File expenseImage) {
		this.expenseImage = expenseImage;
	}


	public List<String> getPaymentTypeList() {
		return paymentTypeList;
	}


	public void setPaymentTypeList(List<String> paymentTypeList) {
		this.paymentTypeList = paymentTypeList;
	}


	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;  
	}


	public HttpServletRequest getRequest() {
		return request;
	}


	public void setRequest(HttpServletRequest request) {
		this.request = request;
	}


	public String getAccountId() {
		return accountId;
	}


	public void setAccountId(String accountId) {
		this.accountId = accountId;
	}


	public Map<String, String> getAccountList() {
		return accountList;
	}


	public void setAccountList(Map<String, String> accountList) {
		this.accountList = accountList;
	}


	public static long getSerialversionuid() {
		return serialVersionUID;
	}


}

	
