package com.reallinkbilling.update;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
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.resource.CheckAlreadyAvailable;


public class UpdateCustomer  extends ActionSupport implements SessionAware{

	/**
	 * 
	 */
	private static final long serialVersionUID = -5130010812118775769L;
	
	private HttpSession session;	
	private String cutomerType;
	private String custName;
	private String custMobileNumber;
	private String custNameMarathi;
	private String custSecondaryMobileNumber;
	private String billingAddressMrathi;
	private String email;
	private String GSTINumber;
	private String TINumber;
	private String PANumber;
	private String BillingAddress;
	private String birthDate;
	private String creditLimit;
	private String custAddDate;
	private List<String> customerTypeList = new ArrayList<String>();
	private String key;
	private SessionMap<String,Object> sessionMap;  

	private File customerImage;
	
	private Map<String,String> customerSearchOptionList = new HashMap<String,String>();
	private String customerSearchOption;
	private String defaultValue;
	
	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{
	        	
	        	customerSearchOptionList.put("BYNAME", "BY NAME");
				customerSearchOptionList.put("BYMOBILE", "BY MOBILE");
				customerSearchOptionList.put("BYADDRESS","BY ADDRESS");
				setDefaultValue("BYNAME");
				setCustomerSearchOption("BYNAME");
				
	        	Connection connection = null;
				PreparedStatement preparedStatement= null;

				String shopId = (String) this.getSessionMap().get("shopId");
	    		String shopCode = (String) this.getSessionMap().get("shopCode");
	    		
				String custId = EncryptionDecryption.decrypt(this.getKey());
				String sql = "";
				String db = (String) this.getSessionMap().get("db");
				FileInputStream fis = null;
				if(this.getCustomerImage() != null)
				{
				  fis =  new FileInputStream(this.getCustomerImage());
				}
					try
					{
						
						connection = GetDBConnection.getDBConnection(db);
						
						System.out.println(this.getGSTINumber());
						
						if(this.getGSTINumber() == null || getGSTINumber().equals(""))
						{
							setGSTINumber("NA");
						}
						if(this.getTINumber() == null || this.getTINumber().equals(""))
						{
							setTINumber("NA");
						}
						if(this.getPANumber() == null || getPANumber().equals(""))
						{
							setPANumber("NA");
						}
						if(this.getCreditLimit() == null || getCreditLimit().equals(""))
						{
							setCreditLimit("0");
						}
						
						if(this.getCustomerImage() != null)
						{
							sql = "UPDATE "
									+ "shop_customer_master "
									+ "SET "
									+ "customer_name=?,"
									+ "cust_name_marathi = ?,"
									+ "mobile_number=?,"
									+ "cust_secondary_mobile = ?,"									
									+ "gst_number=?,"
									+ "tin_number=?,"
									+ "pan_number=?,"
									+ "customer_type = ?,"
									+ "billing_address=?,"
									+ "billing_address_marathi = ?,"
									+ "birth_date=STR_TO_DATE(?, '%d-%m-%Y'),"
									+ "credit_limit=?,"
									+ "customerimage=? "								
									+ "WHERE "
									+ "shop_id = ? "
									+ "AND "
									+ "shop_code = ? "
									+ "AND "
									+ "customer_id = ?";
									
							
									
							
							preparedStatement = connection.prepareStatement(sql);						
							preparedStatement.setString(1, this.getCustName().trim().toUpperCase());
							preparedStatement.setString(2, this.getCustNameMarathi().trim());
							preparedStatement.setString(3, this.getCustMobileNumber().trim());
							preparedStatement.setString(4, this.getCustSecondaryMobileNumber().trim());
							preparedStatement.setString(5, this.getGSTINumber().trim().toUpperCase());
							preparedStatement.setString(6, this.getTINumber().trim().toUpperCase());
							preparedStatement.setString(7, this.getPANumber().trim().toUpperCase());
							preparedStatement.setString(8, this.getCutomerType());
							preparedStatement.setString(9, this.getBillingAddress().trim().toUpperCase());
							preparedStatement.setString(10, this.getBillingAddressMrathi().trim());
							preparedStatement.setString(11, this.getBirthDate());
							preparedStatement.setString(12, this.getCreditLimit().trim());	
							preparedStatement.setBinaryStream(13, fis,(int)getCustomerImage().length() );
							preparedStatement.setString(14, shopId);
							preparedStatement.setString(15, shopCode);
							preparedStatement.setString(16, custId);
							
						
						}
						else
						{
							sql = "UPDATE "
									+ "shop_customer_master "
									+ "SET "
									+ "customer_name=?,"
									+ "cust_name_marathi = ?,"
									+ "mobile_number=?,"
									+ "cust_secondary_mobile = ?,"									
									+ "gst_number=?,"
									+ "tin_number=?,"
									+ "pan_number=?,"
									+ "customer_type = ?,"
									+ "billing_address=?,"
									+ "billing_address_marathi = ?,"
									+ "birth_date=STR_TO_DATE(?, '%d-%m-%Y'),"
									+ "credit_limit=? "	
									+ "WHERE "
									+ "shop_id = ? "
									+ "AND "
									+ "shop_code = ? "
									+ "AND "
									+ "customer_id = ?";
							
									
							
							preparedStatement = connection.prepareStatement(sql);						
						
							preparedStatement.setString(1, this.getCustName().trim().toUpperCase());
							preparedStatement.setString(2, this.getCustNameMarathi().trim());
							preparedStatement.setString(3, this.getCustMobileNumber().trim());
							preparedStatement.setString(4, this.getCustSecondaryMobileNumber().trim());
							preparedStatement.setString(5, this.getGSTINumber().trim().toUpperCase());
							preparedStatement.setString(6, this.getTINumber().trim().toUpperCase());
							preparedStatement.setString(7, this.getPANumber().trim().toUpperCase());
							preparedStatement.setString(8, this.getCutomerType());
							preparedStatement.setString(9, this.getBillingAddress().trim().toUpperCase());
							preparedStatement.setString(10, this.getBillingAddressMrathi().trim());
							preparedStatement.setString(11, this.getBirthDate());
							preparedStatement.setString(12, this.getCreditLimit().trim());				
							preparedStatement.setString(13, shopId);
							preparedStatement.setString(14, shopCode);
							preparedStatement.setString(15, custId);
							
						
							
							
						}
						
						
						int i = preparedStatement.executeUpdate();
						
						
						if(i>0)
						{
							result = "success";
							addActionMessage("Customer details updated successfully !");
						}
						else
						{
							result = "error";
							addActionError("Error ! Customer details not updated ! Please try again !");
						}
						
						
						
					}catch (SQLException e) {
						result = "error";
						e.printStackTrace();
						addActionError(e.getErrorCode()+" || "+e.getMessage() +" || Customer details not updated !");
					} catch (IOException e) {
						e.printStackTrace();
						result = "error";						
						addActionError(e.getMessage()+" || "+e.getCause()+" || Customer details not updated !");
					}finally {
						
						if(preparedStatement != null)
						{
							try {preparedStatement.close();} catch (SQLException e) {}
						}
						if(connection != null)
						{
							
							try {connection.close();}catch (SQLException e) {}
						}
						
					}
	        	
	        	if(fis != null)
	        	{
	        		try
	        		{
	        			fis.close();
	        		}
	        		catch(IOException ioe)
	        		{
	        			
	        		}
	        	}
	        	
	        	
	        }
	      
        	
	        return result;
	}

	
	public void validate() {
		
		this.getCustomerTypeList().add("REGULER");
    	this.getCustomerTypeList().add("RETAILER");
    	this.getCustomerTypeList().add("DEALER");
    	
    	
    	String custId = EncryptionDecryption.decrypt(this.getKey());
		
		if(getCustName().equals("") || getCustMobileNumber().equals("") || getBillingAddress().equals(""))
		{
			addActionError("Please provide details for fields marked with (*) astrick!");
		}
		
		if(!hasActionErrors())
		{
			if(!getCustMobileNumber().equals(""))
			{
				if(getCustMobileNumber().length() >10)
				{
					addActionError("Please Provide correct mobile number ! (10 digit)");
				}
			}
		}
		if(!hasActionErrors())
		{
			String isCustomerAdded = "false";
			
			String [] result = new String[2];
			String condition  = " AND customer_id <> '"+custId+"' ";
			result = new CheckAlreadyAvailable().checkAvaibility("shop_customer_master", "mobile_number", condition, this.getCustMobileNumber(), this.getSessionMap());
			
			isCustomerAdded = result[0];
			
			if(isCustomerAdded.equals("true"))
			{
				addActionError("Customer is already added with same mobile number!");
			}				
			
		}
		if(!hasActionErrors())
		{
			String isCustomerAdded = "false";
			
			String [] result = new String[2];
			String condition  = " AND customer_id <> '"+custId+"' ";
			result = new CheckAlreadyAvailable().checkAvaibility("shop_customer_master", "customer_name", condition, getCustName(), this.getSessionMap());
			
			isCustomerAdded = result[0];
			
			if(isCustomerAdded.equals("true"))
			{
				addActionError("Customer is already added with same name !");
			}				
			
		}
		if(!hasActionErrors())
		{
			if(!getCreditLimit().equals(""))
			{
				try
				{
					Integer.parseInt(getCreditLimit());
					
				}catch(NumberFormatException nfe)
				{
					addActionError("Please provide correct credit limit amount !");
				}
			}
		}
	}

	public HttpSession getSession() {
		return session;
	}


	public void setSession(HttpSession session) {
		this.session = session;
	}


	public String getCustAddDate() {
		return custAddDate;
	}


	public void setCustAddDate(String custAddDate) {
		this.custAddDate = custAddDate;
	}


	public String getCustName() {
		return custName;
	}


	public void setCustName(String custName) {
		this.custName = custName;
	}


	public String getCustMobileNumber() {
		return custMobileNumber;
	}


	public void setCustMobileNumber(String custMobileNumber) {
		this.custMobileNumber = custMobileNumber;
	}


	public String getEmail() {
		return email;
	}


	public void setEmail(String email) {
		this.email = email;
	}

	

	public String getCreditLimit() {
		return creditLimit;
	}


	public void setCreditLimit(String creditLimit) {
		this.creditLimit = creditLimit;
	}


	public String getGSTINumber() {
		return GSTINumber;
	}


	public void setGSTINumber(String gSTINumber) {
		GSTINumber = gSTINumber;
	}


	public String getTINumber() {
		return TINumber;
	}


	public void setTINumber(String tINumber) {
		TINumber = tINumber;
	}


	public String getPANumber() {
		return PANumber;
	}


	public void setPANumber(String pANumber) {
		PANumber = pANumber;
	}


	public String getBillingAddress() {
		return BillingAddress;
	}


	public void setBillingAddress(String billingAddress) {
		BillingAddress = billingAddress;
	}


	public String getBirthDate() {
		return birthDate;
	}


	public void setBirthDate(String birthDate) {
		this.birthDate = birthDate;
	}


	public File getCustomerImage() {
		return customerImage;
	}


	public void setCustomerImage(File customerImage) {
		this.customerImage = customerImage;
	}


	public String getKey() {
		return key;
	}


	public void setKey(String key) {
		this.key = key;
	}


	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 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 String getCutomerType() {
		return cutomerType;
	}


	public void setCutomerType(String cutomerType) {
		this.cutomerType = cutomerType;
	}


	public List<String> getCustomerTypeList() {
		return customerTypeList;
	}


	public void setCustomerTypeList(List<String> customerTypeList) {
		this.customerTypeList = customerTypeList;
	}


	public static long getSerialversionuid() {
		return serialVersionUID;
	}


	public String getCustNameMarathi() {
		return custNameMarathi;
	}


	public void setCustNameMarathi(String custNameMarathi) {
		this.custNameMarathi = custNameMarathi;
	}


	public String getCustSecondaryMobileNumber() {
		return custSecondaryMobileNumber;
	}


	public void setCustSecondaryMobileNumber(String custSecondaryMobileNumber) {
		this.custSecondaryMobileNumber = custSecondaryMobileNumber;
	}


	public String getBillingAddressMrathi() {
		return billingAddressMrathi;
	}


	public void setBillingAddressMrathi(String billingAddressMrathi) {
		this.billingAddressMrathi = billingAddressMrathi;
	}

	

}
