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.Map;

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 UpdateCustOpeningBalance extends ActionSupport implements SessionAware{

	/**
	 * 
	 */
	private static final long serialVersionUID = -1793856353673931057L;
	private String key;
	private SessionMap<String,Object> sessionMap;  
	private String openingBalanceDate;
	private Float amount;
	private String custName;
	private String custAddress;
	
	public String execute(){
		
		String result = "login";
		
		 
	        if(this.getSessionMap()==null || this.getSessionMap().get("login")==null){ 
	        	addActionMessage("Please Login First !!!");
	        	result = "login";
	        }  
	        else{
	        	
	        	
	        	String fullUserName = (String) this.getSessionMap().get("userFullName");
	        	
	        	String splitUserName [] = new String[5];
	        	
	        	String updatedBy = "";
	        	try
	        	{
	        		splitUserName = fullUserName.split(" ");
	        		updatedBy = splitUserName[0];
	        		
	        	}catch(Exception e)
	        	{
	        		updatedBy =fullUserName;
	        	}
	        	
	        	
	        	java.util.Date date = new java.util.Date();
      	      long t = date.getTime();	        	     
      	      java.sql.Time time = new java.sql.Time(t);
	         	
	        	String custId = EncryptionDecryption.decrypt(this.getKey());
	        	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 {
	       			
	       			
					connection = GetDBConnection.getDBConnection(db);
					
					
					sql = "SELECT "
							+ " * FROM "
							+ "shop_cust_close_open_bal_master "
							+ "WHERE "
							+ "customer_id = ? "
							+ "AND "
							+ "shop_id = ? "
							+ "AND "
							+ "shop_code = ? ";
					
					preparedStatement = connection.prepareStatement(sql);
					
					preparedStatement.setString(1, custId);
					preparedStatement.setString(2, shopId);
					preparedStatement.setString(3, shopCode);
					
					resultSet = preparedStatement.executeQuery();
					
					boolean isAdded = false;
					
					if(resultSet.next())
					{
						isAdded = true;
					}
					
					if(resultSet != null)
					{
						resultSet.close();
						resultSet = null;
					}
					if(preparedStatement !=null)
					{
						preparedStatement.close();
						preparedStatement = null;
					}
					
					if(isAdded)
					{
						sql = "UPDATE "
								+ "shop_cust_close_open_bal_master "
								+ "SET "
								+ "opening_bal_update_date = STR_TO_DATE(?,'%d-%m-%Y'),"
								+ "opening_bal_update_time = ?,"
								+ "opening_balance = ?,"
								+ "updated_by = ? "
								+ "WHERE "
								+ "shop_id = ? "
								+ "AND "
								+ "shop_code = ? "
								+ "AND "
								+ "customer_id = ? ";
						
						preparedStatement = connection.prepareStatement(sql);
						
						preparedStatement.setString(1, this.getOpeningBalanceDate());
						preparedStatement.setTime(2, time);
						preparedStatement.setFloat(3, this.getAmount());
						preparedStatement.setString(4, updatedBy);
						preparedStatement.setString(5, shopId);
						preparedStatement.setString(6, shopCode);
						preparedStatement.setString(7, custId);
						
						
						int i = preparedStatement.executeUpdate();
						
						if(i > 0)
						{
							result = SUCCESS;
							
							addActionMessage("OPEING BALANCE UPDATED SUCCESSFULLY!");
						}
						
					}
					else
					{
						sql = "INSERT INTO "
								+ "shop_cust_close_open_bal_master "							
								+ "("
								+ "customer_id,"
								+ "shop_id,"
								+ "shop_code,"
								+ "customer_name,"
								+ "opening_bal_update_date,"
								+ "opening_bal_update_time,"
								+ "opening_balance,"
								+ "closing_bal_update_date,"
								+ "cloasing_bal_update_time,"
								+ "cloasing_balance,"
								+ "updated_by) "
								+ "VALUES "
								+ "(?,?,?,?,STR_TO_DATE(?,'%d-%m-%Y'),?,?,STR_TO_DATE(?,'%d-%m-%Y'),?,?,?)";
						
						preparedStatement = connection.prepareStatement(sql);
						
						preparedStatement.setInt(1, Integer.parseInt(custId));
						preparedStatement.setString(2, shopId);
						preparedStatement.setString(3, shopCode);
						preparedStatement.setString(4, this.getCustName());
						preparedStatement.setString(5, this.getOpeningBalanceDate());
						preparedStatement.setTime(6, time);
						preparedStatement.setFloat(7, this.getAmount());
						preparedStatement.setString(8, this.getOpeningBalanceDate());
						preparedStatement.setTime(9, time);
						preparedStatement.setFloat(10, this.getAmount());
						preparedStatement.setString(11, updatedBy);
						
						int i = preparedStatement.executeUpdate();
						
						if(i > 0)
						{
							result = SUCCESS;
							
							addActionMessage("OPENING BALANCE FOR CUSTOMER "+this.getCustName()+" UPDATED SUCCESSFULLY!");
						}
					}
	       		
	       		}
	       		catch (SQLException e) {
	        		result = ERROR;				
	        		addActionError(e.getErrorCode()+"||"+e.getMessage()+"|| SOME ERROR");
		
        		} 
	       		catch (IOException e) {
					
					result = ERROR;
					addActionError(e.getMessage()+"|| SOME ERROR");
				}	
	   			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.getOpeningBalanceDate() == null || this.getOpeningBalanceDate().equals(""))
    {
    	addActionError("Pease provide opeing 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 static long getSerialversionuid() {
		return serialVersionUID;
	}




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 String getCustName() {
		return custName;
	}




	public void setCustName(String custName) {
		this.custName = custName;
	}




public String getCustAddress() {
		return custAddress;
	}

	public void setCustAddress(String custAddress) {
		this.custAddress = custAddress;
	}

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;  
}
}
