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.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
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.bulksmsgateway.AddBulkSMSGatewayResponseToDB;
import com.reallinkbilling.bulksmsgateway.SendBulkSMSGatewayMessage;
import com.reallinkbilling.db.GetDBConnection;
import com.reallinkbilling.resource.CheckAlreadyAvailable;
import com.realllinkbilling.message.AddTextLocalResponseToDB;
import com.realllinkbilling.message.SendTextLocalMessage;

public class AddNewCustomer  extends ActionSupport implements SessionAware{

	/**
	 * 
	 */
	private static final long serialVersionUID = -5130010812118775769L;
	
	private HttpSession session;
	private String cutomerType;
	private String custName;
	private String custNameMarathi;
	private String custSecondaryMobileNumber;
	private String custMobileNumber;
	private String email;
	private String GSTINumber;
	private String TINumber;
	private String PANumber;
	private String BillingAddress;
	private String billingAddressMrathi;
	private String birthDate;
	private String creditLimit;
	private List<String> customerTypeList = new ArrayList<String>();
	private boolean sendSMS;
	private File customerImage;
	private Map<String,String> customerSearchOptionList = new HashMap<String,String>();
	private String customerSearchOption;
	private String defaultValue;
	private SessionMap<String,Object> sessionMap;  

	
	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");
	    		
	        	Date d = new Date();
	        	SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy");
	        	String custAddDate = dateFormat.format(d);

	        	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) session.getAttribute("db");
				FileInputStream fis  = null;
				if(this.getCustomerImage() != null)
				{
				 fis =  new FileInputStream(this.getCustomerImage());
				}
			
					try
					{
					
						connection = GetDBConnection.getDBConnection(db);
						
						sql = "SELECT "
								+ "customer_id "
								+ "FROM "
								+ "shop_customer_master "
								+ "WHERE "
								+ "shop_id = ? "
								+ "AND "
								+ "shop_code = ? "
								+ "ORDER BY "
								+ "customer_id "
								+ "DESC LIMIT 1";
						
					
					preparedStatement = connection.prepareStatement(sql);
					preparedStatement.setString(1, shopId);
					preparedStatement.setString(2, shopCode);
					
					resultSet = preparedStatement.executeQuery();
						

						int newCustomerId = 1;
						if(resultSet.next())
						{
							if(!(resultSet.getString(1) == null))
							{
								newCustomerId = resultSet.getInt(1) + 1;
								
								
							}
							
						}
						
						
						if(resultSet != null)
						{
							resultSet.close();
							resultSet = null;
						
						}
						if(preparedStatement != null)
						{
							preparedStatement.close();
							preparedStatement = null;
						}
						
						
						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");
						}
						
						sql = "INSERT INTO "
								+ "shop_customer_master "
								+ "("
								+ "customer_id,"
								+ "shop_id,"
								+ "shop_code,"
								+ "add_date,"
								+ "customer_name,"
								+ "cust_name_marathi,"
								+ "mobile_number,"
								+ "cust_secondary_mobile,"
								+ "gst_number,"
								+ "pan_number,"
								+ "tin_number,"
								+ "customer_type,"
								+ "billing_address,"
								+ "billing_address_marathi,"
								+ "birth_date,"
								+ "credit_limit,"
								+ "customer_image) "
								+ "values "
								+ "(?,?,?,STR_TO_DATE(?, '%d-%m-%Y'),?,?,?,?,?,?,?,?,?,?,STR_TO_DATE(?, '%d-%m-%Y'),?,?)";
						
						preparedStatement = connection.prepareStatement(sql);
						
						preparedStatement.setInt(1, newCustomerId);
						preparedStatement.setString(2, shopId);
						preparedStatement.setString(3, shopCode);
						preparedStatement.setString(4, custAddDate);
						preparedStatement.setString(5, this.getCustName().trim().toUpperCase());
						preparedStatement.setString(6, this.getCustNameMarathi().trim());
						preparedStatement.setString(7, this.getCustMobileNumber().trim());
						preparedStatement.setString(8, this.getCustSecondaryMobileNumber().trim());
						preparedStatement.setString(9, this.getGSTINumber().trim().toUpperCase());
						preparedStatement.setString(10, this.getPANumber().trim().toUpperCase());
						preparedStatement.setString(11, this.getTINumber().trim().toUpperCase());
						preparedStatement.setString(12, this.getCutomerType());
						preparedStatement.setString(13, this.getBillingAddress().trim().toUpperCase());
						preparedStatement.setString(14, this.getBillingAddressMrathi().trim().toUpperCase());						
						preparedStatement.setString(15, this.getBirthDate());
						preparedStatement.setString(16, this.getCreditLimit());
						if(this.getCustomerImage() != null)
						{
							preparedStatement.setBinaryStream(17, fis,(int)this.getCustomerImage().length());
						}else
						{
							preparedStatement.setBinaryStream(17, null);
						}
						
						int i = preparedStatement.executeUpdate();
						
						if(i>0)
						{
							/*if(this.isSendSMS())
							{
								
							
								
							String messageServiceProvider = "BULKSMSGATEWAY";

							String messageApiKey = (String) this.getSessionMap().get("message_key");
    						String messageSendrId = (String) this.getSessionMap().get("message_sender_id");
    	        			
    	        			String [] templateIdDetails = new String[3];
    	        			String templateId = "";
    	        			String brandName = "";
    	        			
    	        			HashMap<String,String> templateList = (HashMap<String,String>)this.getSessionMap().get("template_map_list");
    	        			String msg= "";
    	        			boolean allOkSMSSettings = true;
    	        			

    	        			String mobileNumber = this.getCustMobileNumber().trim();
    	        			
    	        			 	try{
	    	        				
	    	        				templateIdDetails = templateList.get("CUSTOMER_WELCOME_MESSAGE").split("#");
	    	        				templateId = templateIdDetails[0];
	    	        				brandName = templateIdDetails[1];
			    	        		msg = brandName
			    	        				+"\n"+this.getSessionMap().get("shopnamemarathi")+" à¤®à¤§à¥�à¤¯à¥‡ à¤†à¤ªà¤²à¥‡ à¤¸à¤¹à¤°à¥�à¤· à¤¸à¥�à¤µà¤¾à¤—à¤¤!"
			    	        				+"\nà¤†à¤®à¥�à¤¹à¤¾à¤²à¤¾ à¤†à¤ªà¤²à¥€ à¤¸à¥‡à¤µà¤¾ à¤•à¤°à¤£à¥�à¤¯à¤¾à¤šà¥€ à¤¸à¤‚à¤§à¥€ à¤¦à¤¿à¤²à¥�à¤¯à¤¾à¤¬à¤¦à¥�à¤¦à¤² à¤†à¤­à¤¾à¤°à¥€ à¤†à¤¹à¥‹à¤¤!"
			    	        				+"\nà¤­à¤µà¤¿à¤·à¥�à¤¯à¤¾à¤¤ à¤†à¤ªà¤£à¤¾à¤‚à¤¸ à¤¸à¤°à¥�à¤µà¥‹à¤¤à¥�à¤¤à¤® à¤¸à¥‡à¤µà¤¾ à¤¦à¥‡à¤£à¥�à¤¯à¤¾à¤¸à¤¾à¤ à¥€ à¤†à¤®à¥�à¤¹à¥€ à¤•à¤Ÿà¤¿à¤¬à¤¦à¥�à¤§ à¤†à¤¹à¥‹à¤¤."
			    	        				+"\nà¤¸à¤‚à¤ªà¤°à¥�à¤•:"+this.getSessionMap().get("shopcustcarenumber");
			    	        			
		    	        			}catch (Exception e) {
			        					allOkSMSSettings = false;
		    	        			}
    	        			 	
    	        	    	
    	        			if(messageServiceProvider.equals("TEXTLOCAL"))
    						{
							
    							
    	    	        			String resp = new SendTextLocalMessage().sendSms(mobileNumber, msg);
    	    	        			
    		    	        			if(resp.contains("Invalid"))
    		    	        			{
    										
    										addActionMessage("Message Not Sent. Invalid Number !!!");
    										
    									}
    									else
    									{
    											AddTextLocalResponseToDB responseToDB = new AddTextLocalResponseToDB();
    											Map<String,String> responseDetails = responseToDB.addTextLocalResponseToDB(resp, mobileNumber, messageServiceProvider,"NEW-CUSTOMER");
    											if(responseDetails != null)
    			    	        				{
    			    	        					String dbAdded = responseDetails.get("DBADDED");
    			    	        					
    			    	        					if(dbAdded.equals("TRUE"))
    			    	        					{
    			    	        						addActionMessage("Message details added!" + responseDetails.get("MESSAGE"));
    			    	        					}
    			    	        					else
    			    	        					{
    			    	        						addActionError("Message details not added! "+responseDetails.get("MESSAGE"));
    			    	        					}
    			    	        				}
    									}
    							
    					}
						else if(messageServiceProvider.equals("BULKSMSGATEWAY") && allOkSMSSettings)
						{
							
								try
								{
								String [] keyDetails =  messageApiKey.split("#");
								String userName = keyDetails[0];
								String password = keyDetails[1];
								
								String resp  = SendBulkSMSGatewayMessage.sendLanguageSms(userName, password, mobileNumber, msg, messageSendrId, templateId);
	    	        			if(resp.contains("failed"))
	    	        			{
	    	        				addActionError("Counldn't send message" + resp);
	    	        			}
	    	        			else
	    	        			{
	    	        				AddBulkSMSGatewayResponseToDB gatewayResponseToDB = new AddBulkSMSGatewayResponseToDB();
	    	        				Map<String,String> responseDetails = gatewayResponseToDB.addBulkSMSGatewayResponseToDB(this.getSessionMap(),resp, mobileNumber, messageServiceProvider, messageSendrId, msg, "NEW-CUSTOMER");
	    	        				
	    	        				if(responseDetails != null)
	    	        				{
	    	        					String dbAdded = responseDetails.get("DBADDED");
	    	        					
	    	        					if(dbAdded.equals("TRUE"))
	    	        					{
	    	        						addActionMessage("Message details added!" + responseDetails.get("MESSAGE"));
	    	        					}
	    	        					else
	    	        					{
	    	        						addActionError("Message details not added! "+responseDetails.get("MESSAGE"));
	    	        					}
	    	        				}
	    	        				
	    	        			}
    									
								}catch (Exception e) {
									addActionError("Couldn't send message to customer!"+e.getMessage()+"|"+e.getCause());
								}
						}
    	        	//
							}*/
						
							result = "success";
							addActionMessage("Customer details added successfully !");
						}
						else
						{
							result = "error";
							addActionError("Error ! Customer details not added ! Please try again !");
						}
						
						
						
					}catch (SQLException e) {
						e.printStackTrace();
						result = "error";
						
						addActionError(e.getErrorCode()+" || "+e.getMessage() +" || Customer details not added !");
					} catch (IOException e) {
						
						result = "error";						
						addActionError(e.getMessage()+" || "+e.getCause()+" || Customer 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)
	        	{
	        		fis.close();
	        	}
	        	
	        }
	        return result;
	}

	
	public void validate() {
		

    	this.getCustomerTypeList().add("REGULER");
    	this.getCustomerTypeList().add("RETAILER");
    	this.getCustomerTypeList().add("DEALER");
		
		if(getCustName().equals("") || getCustMobileNumber().equals("") || getBillingAddress().equals(""))
		{
			addActionError("Please provide details for fields marked with (*) astrick!");
		}
		
		if(!hasActionErrors())
		{
			if(this.getCutomerType().equals(""))
			{
				addActionError("please select customer type!");
			}
		}
		
		if(!hasActionErrors())
		{
			if(!getCustMobileNumber().equals(""))
			{
				if(getCustMobileNumber().length() >10)
				{
					addActionError("Please Provide correct mobile number ! (10 digit)");
				}
			}
		}
		if(!hasActionErrors())
		{
			String isCustomerAdded = "false";
			
			if(!this.getCustMobileNumber().equals("9999999999"))
			{
			
				String [] result = new String[2];
				String condition  = "NA";
				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  = "NA";
			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 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 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 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;  
	}


	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 boolean isSendSMS() {
		return sendSMS;
	}


	public void setSendSMS(boolean sendSMS) {
		this.sendSMS = sendSMS;
	}


	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;
	}
	
	

}
