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.HashMap;
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;

public class UpdateSupplierOpeningBalance extends ActionSupport implements SessionAware{

	/**
	 * 
	 */
	private static final long serialVersionUID = -6492235460509123538L;
	
	private String key;
	private String supplierName;
	private String openingBalanceDate;
	private Float amount;
	
	private Map<String,String> customerSearchOptionList = new HashMap<String,String>();
	private String customerSearchOption;
	private String defaultValue;
	private SessionMap<String,Object> sessionMap;  
	
	
	private HttpSession session;
	
	
	public String execute() throws IOException{
		 
		String result = "login";
		session=ServletActionContext.getRequest().getSession(false); 
		
	        if(session==null || session.getAttribute("login")==null){ 
	        	addActionMessage("Please Login First !!!");
	        	result = "login";
	        }  
	        else{
	        	
	        	String shopId = (String) this.getSessionMap().get("shopId");
	    		String shopCode = (String) this.getSessionMap().get("shopCode");
	    		
	        	customerSearchOptionList.put("BYNAME", "BY NAME");
	        	customerSearchOptionList.put("BYMOBILE", "BY MOBILE");
	        	customerSearchOptionList.put("BYADDRESS","BY ADDRESS");
				setCustomerSearchOption("BYNAME");
				setDefaultValue("BYNAME");
	        	
	        	Connection connection = null;
				PreparedStatement preparedStatement= null;
				ResultSet resultSet = null;
				
				String sql = "";
				String db = (String) this.getSessionMap().get("db");
				String supplierId = EncryptionDecryption.decrypt(this.getKey());
				
					try
					{
						
						connection = GetDBConnection.getDBConnection(db);
						
						String user = (String) this.getSessionMap().get("userFullName");
						String userName = "";
						
						try
						{
							userName = user.split(" ")[0];
						}catch(Exception e)
						{
							userName = user;
						}
						
						
						
		        		
		        		sql = "SELECT "
		        				+ "supplier_id,"
		        				+ "supplier_name,"
		        				+ "opening_balance_amount "
		        				+ "FROM "
		        				+ "shop_supplier_open_close_balance_master "
		        				+ "WHERE "
		        				+ "shop_id = ? "
		        				+ "AND "
		        				+ "shop_code = ? "
		        				+ "AND "
		        				+ "supplier_id = ? ";
		        		
		        		preparedStatement = connection.prepareStatement(sql);
		        		
		        		preparedStatement.setString(1, shopId);
		        		preparedStatement.setString(2, shopCode);
		        		preparedStatement.setString(3, supplierId);
		        		
		        		resultSet = preparedStatement.executeQuery();
		        		
		        		PreparedStatement updateOpeningBalPSMT = null;
		        		PreparedStatement insertOpeningBalPSMT = null;
		        		
		        		java.util.Date date = new java.util.Date();
		        	      long t = date.getTime();	        	     
		        	      java.sql.Time time = new java.sql.Time(t);
		        	      
		        		int rowInsertedUpdatedCount = 0;
		        		if(resultSet.next())
		        		{
		        			
		        			sql = "UPDATE "
		        					+ "shop_supplier_open_close_balance_master "
		        					+ "SET "
		        					+ "opening_balance_date = DATE_FORMAT(?,'%d-%m-%Y'),"
		        					+ "opening_balance_amount = ?,"
		        					+ "entry_updated_by = ? "
		        					+ "WHERE "
		        					+ "shop_id = ? "
		        					+ "AND "
		        					+ "shop_code = ? "
		        					+ "AND "
		        					+ "supplier_id = ? ";
		        			
		        			updateOpeningBalPSMT = connection.prepareStatement(sql);
		        			
		        			updateOpeningBalPSMT.setString(1, this.getOpeningBalanceDate());
		        			updateOpeningBalPSMT.setFloat(2, this.getAmount());
		        			updateOpeningBalPSMT.setString(3, userName);
		        			updateOpeningBalPSMT.setString(4, shopId);
		        			updateOpeningBalPSMT.setString(5, shopCode);
		        			updateOpeningBalPSMT.setString(6, supplierId);
		        			rowInsertedUpdatedCount = updateOpeningBalPSMT.executeUpdate();
		        			
		        		}
		        		else
		        		{
		        			
		        			
		        			sql = "INSERT INTO "
		        					+ "shop_supplier_open_close_balance_master "
		        					+ "("
		        					+ "supplier_id,"
		        					+ "supplier_name,"
		        					+ "shop_id,"
		        					+ "shop_code,"
		        					+ "opening_balance_date,"
		        					+ "opening_balance_time,"
		        					+ "opening_balance_amount,"
		        					+ "closeing_balance_date,"
		        					+ "closing_balance_time,"
		        					+ "closing_balance_amount,"
		        					+ "entry_updated_by) "
		        					+ "VALUES "
		        					+ "(?,?,?,?,STR_TO_DATE(?,'%d-%m-%Y'),?,?,STR_TO_DATE(?,'%d-%m-%Y'),?,?,?)";
		        			
		        			insertOpeningBalPSMT = connection.prepareStatement(sql);
		        		
		        			insertOpeningBalPSMT.setString(1, supplierId);
		        			insertOpeningBalPSMT.setString(2, this.getSupplierName());
		        			insertOpeningBalPSMT.setString(3, shopId);
		        			insertOpeningBalPSMT.setString(4, shopCode);		        			
		        			insertOpeningBalPSMT.setString(5, this.getOpeningBalanceDate());
		        			insertOpeningBalPSMT.setTime(6, time);
		        			insertOpeningBalPSMT.setFloat(7, this.getAmount());
		        			insertOpeningBalPSMT.setString(8, this.getOpeningBalanceDate());
		        			insertOpeningBalPSMT.setTime(9, time);
		        			insertOpeningBalPSMT.setFloat(10, this.getAmount());
		        			insertOpeningBalPSMT.setString(11, userName);
		        			
		        			rowInsertedUpdatedCount = insertOpeningBalPSMT.executeUpdate();
		        			
		        		}
		        		
		        		if(updateOpeningBalPSMT != null)
		        		{
		        			updateOpeningBalPSMT.close();
		        			updateOpeningBalPSMT = null;
		        		}
		        		
		        		if(insertOpeningBalPSMT != null)
		        		{
		        			insertOpeningBalPSMT.close();
		        			insertOpeningBalPSMT = null;
		        		}
		        		
		        		if(rowInsertedUpdatedCount > 0)
	        			{
	        				result = "success";
	        				addActionMessage("Suppliers' opening balance details updated successfully!");
	        			}
	        			else
	        			{
	        				result = "error";
	        				addActionError("Error! Supplier opening balance details not updated! Please tey again!");
	        				
	        			}
					}catch (SQLException e) {
						result = "error";
						e.printStackTrace();
						addActionError(e.getErrorCode()+" || "+e.getMessage() +" ||Details not updated !");
					} catch (IOException e) {
						
						result = "error";					
						addActionError(e.getMessage()+" || "+e.getCause()+" || Details 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;
		 
		}
		
		@Override
		public void validate() {
		
			
			customerSearchOptionList.put("BYNAME", "BY NAME");
			customerSearchOptionList.put("BYMOBILE", "BY MOBILE");
			customerSearchOptionList.put("BYADDRESS","BY ADDRESS");
			setDefaultValue("BYNAME");
			setCustomerSearchOption("BYNAME");
			
			if(this.getOpeningBalanceDate().equals(""))
			{
				
				addActionError("Please provide opening balance date!");
			}
			
			if(!hasActionErrors())			
			{
				if(this.getAmount() == null || this.getAmount().equals(""))
				{
					addActionError("Please provide correct amount!");
				}
			}
		}
		

	public String getKey() {
		return key;
	}


	public void setKey(String key) {
		this.key = key;
	}


	public String getSupplierName() {
		return supplierName;
	}


	public void setSupplierName(String supplierName) {
		this.supplierName = supplierName;
	}


	public String getOpeningBalanceDate() {
		return openingBalanceDate;
	}


	public void setOpeningBalanceDate(String openingBalanceDate) {
		this.openingBalanceDate = openingBalanceDate;
	}


	public Float getAmount() {
		return amount;
	}


	public void setAmount(Float amount) {
		this.amount = amount;
	}


	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 void setDefaultValue(String defaultValue) {
		this.defaultValue = defaultValue;
	}


	public HttpSession getSession() {
		return session;
	}


	public void setSession(HttpSession session) {
		this.session = session;
	}


	public static long getSerialversionuid() {
		return serialVersionUID;
	}


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;  
}

	
	
	

}
