package com.reallinkbilling.update;

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.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

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;

public class UpdateAccountEntry extends ActionSupport implements SessionAware{

	/**
	 * 
	 */
	private static final long serialVersionUID = -7979427943932564965L;
	private SessionMap<String,Object> sessionMap;  
	private HttpSession session;
	Map<String,String> accountList = new LinkedHashMap<String,String>();
	List<String> paymentTypeList = new ArrayList<String>();
	
	private String entryDate;
	private String accountId;
	private Float amount;
	private String typeOfPayment;
	private String entryDetails;
	
	private Map<String,String> customerSearchOptionList = new HashMap<String,String>();
	private String customerSearchOption;
	private String defaultValue;
	List<String> entryTypeList = new ArrayList<String>();
	private String entryType;
	private String key;
	
	public String execute() {
		 
		String result = "login";
		
		session=ServletActionContext.getRequest().getSession(false); 
		
	        if(this.getSessionMap()==null || this.getSessionMap().get("login")==null){
	        	
	        	addActionMessage("Please Login First !!!");
	        	result = "login";
	        }  
	        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
				{
					java.util.Date date = new java.util.Date();
	        	      long t = date.getTime();	        	     
	        	      java.sql.Time time = new java.sql.Time(t);
					
					String user = (String) session.getAttribute("userFullName");
					String userName = "";
					
					try
					{
						userName = user.split(" ")[0];
					}catch(Exception e)
					{
						userName = user;
					}
					
					
					String [] keyDetails = EncryptionDecryption.decrypt(this.getKey()).split("#") ;
					
					String entryId = keyDetails[0] ;
					String accountId = keyDetails[1];
					String entryType = keyDetails[2];
					
					connection = GetDBConnection.getDBConnection(db);
					
					
					sql = "SELECT "
							+ "entry_id,"
							+ "account_id,"
							+ "account_number,"
							+ "entry_date,"
							+ "entry_time,"
							+ "entry_type,"
							+ "amount,"
							+ "payment_type,"
							+ "entry_by,"
							+ "entry_details "
							+ "FROM "
							+ "bank_account_credit_debit_master "
							+ "WHERE "
							+ "entry_id = ? "
							+ "AND "
							+ "account_id = ? "
							+ "AND "
							+ "shop_id = ? "
							+ "AND "
							+ "shop_code = ? ";
					
					preparedStatement = connection.prepareStatement(sql);
					preparedStatement.setString(1, entryId);
					preparedStatement.setString(2, accountId);
					preparedStatement.setString(3, shopId);
					preparedStatement.setString(4, shopCode);
					resultSet = preparedStatement.executeQuery();
					
					int m = 0;
					if(resultSet.next())
					{
						
						PreparedStatement  insertIntoDeletedPSMT = null;
						
						String inertDeletedSQL = "INSERT "
								+ "INTO "
								+ "bank_account_credit_debit_updated_entry_master "
								+ "("
								+ "entry_id,"
								+ "shop_id,"
								+ "shop_code,"
								+ "account_id,"
								+ "account_number,"
								+ "entry_date,"
								+ "entry_time,"
								+ "entry_type,"
								+ "amount,"
								+ "payment_type,"
								+ "entry_by,"
								+ "entry_details) "
								+ "VALUES "
								+ "(?,?,?,?,?,?,?,?,?,?,?,?)";
						
						insertIntoDeletedPSMT = connection.prepareStatement(inertDeletedSQL);
						
						insertIntoDeletedPSMT.setString(1, entryId);
						insertIntoDeletedPSMT.setString(2, shopId);
						insertIntoDeletedPSMT.setString(3, shopCode);
						insertIntoDeletedPSMT.setString(4, resultSet.getString(2));
						insertIntoDeletedPSMT.setString(5, resultSet.getString(3));
						insertIntoDeletedPSMT.setString(6, resultSet.getString(4));
						insertIntoDeletedPSMT.setTime(7, time);
						insertIntoDeletedPSMT.setString(8, resultSet.getString(6));
						insertIntoDeletedPSMT.setFloat(9, resultSet.getFloat(7));
						insertIntoDeletedPSMT.setString(10, resultSet.getString(8));
						insertIntoDeletedPSMT.setString(11, userName);
						insertIntoDeletedPSMT.setString(12, resultSet.getString(10));
						
						  m = insertIntoDeletedPSMT.executeUpdate();
						
						if(insertIntoDeletedPSMT != null)
						{
							insertIntoDeletedPSMT.close();
							insertIntoDeletedPSMT = null;
						}
						
					}
					if(resultSet != null)
					{
						resultSet.close();
						resultSet = null;
					}
					if(preparedStatement != null)
					{
						preparedStatement.close();
						preparedStatement = null;
					}
					
					
					String accountNumber = "";
	        		sql = "SELECT "
	        				+ "account_number "
	        				+ "FROM "
	        				+ "bank_account "
	        				+ "WHERE "
	        				+ "account_id  = ? "
	        				+ "AND "
	        				+ "shop_id = ? "
	        				+ "AND "
	        				+ "shop_code = ?";
	        			
	        		preparedStatement = connection.prepareStatement(sql);
	        		
	        		preparedStatement.setString(1, this.getAccountId());
	        		preparedStatement.setString(2, shopId);
	        		preparedStatement.setString(3, shopCode);
	        		
	        		resultSet = preparedStatement.executeQuery();
	        		if(resultSet.next())
	        		{
	        			accountNumber = resultSet.getString(1);
	        		}
	        		
	        		if(resultSet != null)
	        		{
	        			resultSet.close();
	        			resultSet = null;
	        		}
	        		if(preparedStatement!= null)
	        		{
	        			preparedStatement.close();
	        			preparedStatement = null;
	        		}
	        		
					sql = "UPDATE "
							+ "bank_account_credit_debit_master "
							+ "SET "
							+ "account_id = ?,"
							+ "account_number = ?,"
							+ "entry_date = STR_TO_DATE(?,'%d-%m-%Y'),"
							+ "entry_time = ?,"
							+ "entry_type = ?,"
							+ "amount = ?,"
							+ "payment_type = ? ,"
							+ "entry_by = ?,"
							+ "entry_details = ? "
							+ "WHERE "
							+ "entry_id = ? "
							+ "AND "
							+ "account_id = ? "
							+ "AND "
							+ "shop_id = ? "
							+ "AND "
							+ "shop_code = ?";
					
					
					preparedStatement = connection.prepareStatement(sql);
					
					preparedStatement.setString(1, this.getAccountId());
					preparedStatement.setString(2, accountNumber);
					preparedStatement.setString(3, this.getEntryDate());
					preparedStatement.setTime(4, time);
					preparedStatement.setString(5, this.getEntryType());
					preparedStatement.setFloat(6, this.getAmount());
					preparedStatement.setString(7, this.getTypeOfPayment());
					preparedStatement.setString(8, userName);
					preparedStatement.setString(9, this.getEntryDetails());
					preparedStatement.setString(10, entryId);
					preparedStatement.setString(11, accountId);
					preparedStatement.setString(12, shopId);
					preparedStatement.setString(13, shopCode);
					
					
				int k = preparedStatement.executeUpdate();
				
				if(k>0)
				{
					result = SUCCESS;
					addActionMessage("Entry Updated Successfully!");
				}
					
				else
				{
					result = ERROR;
					addActionError("Entry not updated! Please try again!");
				}
				}
				catch (SQLException e) {
					result = "error";
					//e.printStackTrace();
					addActionError(e.getErrorCode()+" || "+e.getMessage() +" || Entry not updated !!!");
				} catch (IOException e) {
					result = "error";
					//e.printStackTrace();
					addActionError(e.getMessage()+" || "+e.getCause()+" || Entry not updated !!!");
				}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;
	}


public void validate() {
	
		this.getEntryTypeList().add("CREDIT");
		this.getEntryTypeList().add("DEBIT");
	
		session=ServletActionContext.getRequest().getSession(false); 
		
		customerSearchOptionList.put("BYNAME", "BY NAME");
    	customerSearchOptionList.put("BYMOBILE", "BY MOBILE");
    	customerSearchOptionList.put("BYADDRESS","BY ADDRESS");
		setCustomerSearchOption("BYNAME");
		setDefaultValue("BYNAME");
		
		this.setAccountList(GetAccountListForDrCr.getAccountList(this.getSessionMap()));        	
    	this.setPaymentTypeList(GetTypeOfPaymentList.getTypeOfPaymentList());
		
		if(this.getAccountId().equals(""))
		{
			addActionError("Please select account number!");
		}
		
		if(!hasActionErrors())
		{
			if(this.getAmount() == null || this.getAmount().equals(""))
			{
				addActionError("Please provide correct amount!");
			}
		}
	}
	


	public Map<String, String> getAccountList() {
		return accountList;
	}



	public void setAccountList(Map<String, String> accountList) {
		this.accountList = accountList;
	}



	public List<String> getPaymentTypeList() {
		return paymentTypeList;
	}



	public void setPaymentTypeList(List<String> paymentTypeList) {
		this.paymentTypeList = paymentTypeList;
	}



	public static long getSerialversionuid() {
		return serialVersionUID;
	}
	


	public HttpSession getSession() {
		return session;
	}


	public void setSession(HttpSession session) {
		this.session = session;
	}


	public String getEntryDate() {
		return entryDate;
	}


	public void setEntryDate(String entryDate) {
		this.entryDate = entryDate;
	}


	public String getAccountId() {
		return accountId;
	}


	public void setAccountId(String accountId) {
		this.accountId = accountId;
	}


	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 getEntryDetails() {
		return entryDetails;
	}


	public void setEntryDetails(String entryDetails) {
		this.entryDetails = entryDetails;
	}


	public Map<String, String> getCustomerSearchOptionList() {
		return customerSearchOptionList;
	}


	public void setCustomerSearchOptionList(Map<String, String> customerSearchOptionList) {
		this.customerSearchOptionList = customerSearchOptionList;
	}


	public String getCustomerSearchOption() {
		return customerSearchOption;
	}


	public void setCustomerSearchOption(String customerSearchOption) {
		this.customerSearchOption = customerSearchOption;
	}


	public String getDefaultValue() {
		return defaultValue;
	}


	public String getKey() {
		return key;
	}


	public void setKey(String key) {
		this.key = key;
	}


	public List<String> getEntryTypeList() {
		return entryTypeList;
	}


	public void setEntryTypeList(List<String> entryTypeList) {
		this.entryTypeList = entryTypeList;
	}


	public String getEntryType() {
		return entryType;
	}


	public void setEntryType(String entryType) {
		this.entryType = entryType;
	}


	public void setDefaultValue(String defaultValue) {
		this.defaultValue = defaultValue;
	}


	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;  
	}
			
}
