package com.reallinkbilling.ajax;

import java.sql.Connection;
import java.sql.PreparedStatement;
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.stonecrusher.infrawhatsappmsg.CheckBalance;
import com.reallinkbilling.bulksmsgateway.AddBulkSMSGatewayResponseToDB;
import com.reallinkbilling.bulksmsgateway.SendBulkSMSGatewayMessage;
import com.reallinkbilling.cipher.EncryptionDecryption;
import com.reallinkbilling.db.GetDBConnection;
import com.stonecrusher.infrawhatsappmsg.SendWhatsAppMessage;
import com.reallinkbilling.utils.WhatsAppSettingsUtil;
import com.realllinkbilling.message.AddTextLocalResponseToDB;
import com.realllinkbilling.message.SendTextLocalMessage;

public class SendOutstandingAmountMessage extends ActionSupport implements SessionAware{

	/**
	 * 
	 */
	private static final long serialVersionUID = 4862566993600989477L;
	private String smsData;
	private String returnMessage;
	private HttpSession session;
	private SessionMap<String,Object> sessionMap;  
	
	@Override
	public String execute(){
		String result = "error";
		
		session=ServletActionContext.getRequest().getSession(false); 
		 
	        if(session==null || session.getAttribute("login")==null){ 
	        	addActionMessage("Please Login First !!!");
	        	result = "error";
	        }  
	        else{
	        	
	        	Connection connection = null;
				PreparedStatement preparedStatement= null;
				
				
				String sql = "";
				String db = (String) session.getAttribute("db");
				
					
					String actualData = EncryptionDecryption.decrypt(smsData);
					
				
					
					String [] data = new String[5]; 
					try
					{
						
						String messageServiceProvider = (String) this.getSessionMap().get("serviceprovider");
						if(messageServiceProvider == null || messageServiceProvider.trim().isEmpty())
						{
							messageServiceProvider = "BULKSMSGATEWAY";
						}
						boolean sendWhatsAppMessage = WhatsAppSettingsUtil.isWhatsAppSendingEnabled(this.getSessionMap());
					
						
						connection = GetDBConnection.getDBConnection(db);
						
						data = actualData.split("-");
						
						
						String mobileNumber = WhatsAppSettingsUtil.resolveTargetMobile(this.getSessionMap(), data[0]);
						
						
						String messageApiKey = (String) this.getSessionMap().get("message_key");
						String messageSendrId = (String) this.getSessionMap().get("message_sender_id");
						String shopId = (String) this.getSessionMap().get("shopId");
						String shopCode = (String) this.getSessionMap().get("shopCode");
	        			
	        			String [] templateIdDetails = new String[3];
	        			String templateId = "";
	        			String brandName = "";
	        			
	        			HashMap<String,String> templateList = (HashMap<String,String>)this.getSessionMap().get("template_map_list");
	        			
	        			boolean allOkSMSSettings = true;
	        			

        			 	try{
	        				
	        				templateIdDetails = templateList.get("CUSTOMER_OUTSTANDING_SMS_ALERT").split("#");
	        				templateId = templateIdDetails[0];
	        				brandName = templateIdDetails[1];
	    	        			
	    	        			
    	        			}catch (Exception e) {
	        					allOkSMSSettings = false;
    	        			}

        			 	String msg = brandName
        			 			+"\nà¤ªà¥�à¤°à¤¿à¤¯ à¤—à¥�à¤°à¤¾à¤¹à¤•,à¤†à¤ªà¤²à¥€ à¤�à¤•à¥‚à¤£ à¤¯à¥‡à¤£à¥‡ à¤¬à¤¾à¤•à¥€ à¤°à¤•à¥�à¤•à¤® : "+data[1]+" à¤°à¥�."
        			 			+"\nà¤•à¥ƒà¤ªà¤¯à¤¾ à¤¬à¤¾à¤•à¥€ à¤°à¤•à¥�à¤•à¤® à¤²à¤µà¤•à¤°à¤¾à¤¤ à¤²à¤µà¤•à¤° à¤œà¤®à¤¾ à¤•à¤°à¤¾à¤µà¥€."
        			 			+"\nà¤¹à¤¿ à¤µà¤¿à¤¨à¤‚à¤¤à¥€.à¤§à¤¨à¥�à¤¯à¤µà¤¾à¤¦! "+this.getSessionMap().get("shopnamemarathi")
        			 			+"\nà¤¸à¤‚à¤ªà¤°à¥�à¤•:"+this.getSessionMap().get("shopcustcarenumber");
        			 	
					if("TEXTLOCAL".equals(messageServiceProvider))
						{
						
							
	    	        			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,"OUTSTANDING");
											if(responseDetails != null)
			    	        				{
			    	        					String dbAdded = responseDetails.get("DBADDED");
			    	        					
			    	        					if("TRUE".equals(dbAdded))
			    	        					{
			    	        						addActionMessage("Message details added!" + responseDetails.get("MESSAGE"));
			    	        					}
			    	        					else
			    	        					{
			    	        						addActionError("Message details not added! "+responseDetails.get("MESSAGE"));
			    	        					}
			    	        				}
									}
							
					}
					else if(!sendWhatsAppMessage)
					{
						addActionMessage("WhatsApp message sending is disabled in settings.");
					}
					else if(!WhatsAppSettingsUtil.isValidMobileNumber(mobileNumber))
					{
						addActionMessage("Invalid Mobile Number ! Cannot send message !");
					}
					else if("INFRAINFOTECH".equals(messageServiceProvider) && allOkSMSSettings)
					{
						String[] tokenData = WhatsAppSettingsUtil.getDefaultTokenDetails(this.getSessionMap());
						if(tokenData != null && tokenData.length >= 3 && !mobileNumber.contains("99999999"))
						{
							try
							{
								String userName = tokenData[0];
								String tokenNumber = tokenData[1];
								String balanceCheckTokenNumber = tokenData[2];
								
								String resp  = SendWhatsAppMessage.sendMessageOnly(userName, mobileNumber, msg, tokenNumber);
	    	        			if(WhatsAppSettingsUtil.isFailedResponse(resp))
	    	        			{
	    	        				addActionError("Counldn't send message" + resp);
	    	        			}
	    	        			else
	    	        			{
	    	        				int bal = CheckBalance.checkBal(userName, balanceCheckTokenNumber);
	    	        				if(resp.toLowerCase().contains("success"))
	    	        				{
	    	        					addActionMessage("WhatsApp Message Sent Successfully! Remaining Message Balance : "+bal);
	    	        				}
	    	        				else
	    	        				{
	    	        					addActionMessage("WhatsApp message response : "+resp);
	    	        				}
	    	        				
	    	        			}
								
							}catch (Exception e) {
								addActionError("Couldn't send message to customer!"+e.getMessage()+"|"+e.getCause());
							}
						}
						else
						{
							addActionError("WhatsApp token mapping not found for defaultWhatsAppNumber.");
						}
					}
					else if("BULKSMSGATEWAY".equals(messageServiceProvider) && 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, "OUTSTANDING");
    	        				
    	        				if(responseDetails != null)
    	        				{
    	        					String dbAdded = responseDetails.get("DBADDED");
    	        					
    	        					if("TRUE".equals(dbAdded))
    	        					{
    	        						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 milk supplier!"+e.getMessage()+"|"+e.getCause());
							}
					}
					
					
						
						
						
					}
					catch(Exception e)
					{
						//e.printStackTrace();
						result = "error";
					}finally
					{
						
						if(preparedStatement != null)
						{
							try {
								preparedStatement.close(); preparedStatement = null;
							} catch (SQLException e) {
								
							}
						}
						
						if(connection != null)
						{
							try {
								connection.close(); connection = null;
							} catch (SQLException e) {
								
							}
						}
						
						
					}
					
		     
		     
			
					
		result = "success";
	        }
		return result;
	}
	public String getSmsData() {
		return smsData;
	}
	public void setSmsData(String smsData) {
		this.smsData = smsData;
	}
	public String getReturnMessage() {
		return returnMessage;
	}
	public void setReturnMessage(String returnMessage) {
		this.returnMessage = returnMessage;
	}
	
	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;  
	}

}
