package com.realllinkbilling.message;

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.fasterxml.jackson.databind.ObjectMapper;
import com.opensymphony.xwork2.ActionSupport;
import com.stonecrusher.infrawhatsappmsg.CheckBalance;
import com.reallinkbilling.DAO.OutstandingMessageSendReportDAO;
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;

public class SendSelectedCreditMessage extends ActionSupport implements SessionAware{

	/**
	 * 
	 */
	private static final long serialVersionUID = 3477252382765835945L;
	
	private HttpSession session;
	private SessionMap<String,Object> sessionMap;
	private List<String> selection = new ArrayList<String>();
	private Map<String,String> customerSearchOptionList = new HashMap<String,String>();
	private String customerSearchOption;
	private List<OutstandingMessageSendReportDAO> messageSendReportList = new ArrayList<OutstandingMessageSendReportDAO>();
	private String defaultValue;
	public String execute()
	{
		String result = "login";
		 session=ServletActionContext.getRequest().getSession(false); 
			
	        if(session==null || session.getAttribute("login")==null){ 
	        	addActionMessage("Please Login First !!!");
	        	result = "login";  
	        
	        }  
	        else{  
	        	
	        
			Connection connection = null;
			PreparedStatement preparedStatement= null;
			ResultSet resultSet = null;
			String sql = "";
			String db = (String) session.getAttribute("db");
			try
			{
				customerSearchOptionList.put("BYNAME", "BY NAME");
	        	customerSearchOptionList.put("BYMOBILE", "BY MOBILE");
	        	customerSearchOptionList.put("BYADDRESS","BY ADDRESS");
				setCustomerSearchOption("BYNAME");
				setDefaultValue("BYNAME");
	        	
				
				
				connection = GetDBConnection.getDBConnection(db);
				
				int messageCount = 0;
				
				for(String s:this.getSelection())
				{
					OutstandingMessageSendReportDAO dao = new OutstandingMessageSendReportDAO();
					String [] smsData = EncryptionDecryption.decrypt(s).split("-");
					
					dao.setCustMobile(smsData[0]);
					dao.setOutStandingAmount(smsData[1]);
					
					
					sql = "SELECT "
							+ "custname,"
							+ "billingaddress "
							+ "FROM "
							+ "customers "
							+ "WHERE "
							+ "mobilenumber = '"+smsData[0]+"'";
					
					preparedStatement = connection.prepareStatement(sql);
					
					resultSet = preparedStatement.executeQuery();
					
					if(resultSet.next())
					{
						dao.setCustName(resultSet.getString(1));
						dao.setCustAddress(resultSet.getString(2));
					}
					
					if(resultSet != null)
					{
						resultSet.close();
						resultSet = null;
					}
					
					if(preparedStatement!= null)
						
					{
						preparedStatement.close();
						preparedStatement = null;
					}
					
					String mobileNumber = smsData[0];
					mobileNumber = WhatsAppSettingsUtil.resolveTargetMobile(this.getSessionMap(), mobileNumber);
					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");
					boolean sendWhatsAppMessage = WhatsAppSettingsUtil.isWhatsAppSendingEnabled(this.getSessionMap());
        			
        			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प्रिय ग्राहक, आपली एकूण येणे बाकी रक्कम : "+smsData[1]+" रु."
    			 			+"\nकृपया बाकी रक्कम लवकरात लवकर जमा करावी."
    			 			+"\nही विनंती. धन्यवाद! "+this.getSessionMap().get("shopnamemarathi")
    			 			+"\nसंपर्क:"+this.getSessionMap().get("shopcustcarenumber");

					String messageServiceProvider = (String) this.getSessionMap().get("serviceprovider");
					if(messageServiceProvider == null || messageServiceProvider.trim().isEmpty())
					{
						messageServiceProvider = "BULKSMSGATEWAY";
					}
					

        			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());
						}
				}
				
					
					this.getMessageSendReportList().add(dao);
				}
				
				if(messageCount > 0)
				{
					result = "success";				
					addActionMessage("Credit message sent to "+messageCount+" customers!");
				}
				else
				{
					result = "error";
					addActionMessage("Messages not sent! Please check internet connection!");
				}
			}
			 catch (SQLException e)
				{
					result = "error";
					
					addActionMessage(e.getErrorCode()+" || "+e.getMessage() +" || MESSAGES NOT SENT !");
				} 
			catch (IOException e) {
					result = "error";
					
					addActionMessage(e.getMessage()+" || "+e.getCause()+" || MESSAGES NOT SENT !");
				}finally {
					if(resultSet !=null)
					{
						try
						{
							resultSet.close();
						}
						catch(SQLException sqe)
						{
							
						}
					}
					if(preparedStatement != null)
					{
						try {preparedStatement.close();} catch (SQLException e) {}
					}
					if(connection != null)
					{
						
						try {connection.close();}catch (SQLException e) {}
					}
					
				}
			result = "success";

	        }
	        
	        return result;
	}


	public List<String> getSelection() {
		return selection;
	}


	public void setSelection(List<String> selection) {
		this.selection = selection;
	}


	public HttpSession getSession() {
		return session;
	}


	public void setSession(HttpSession session) {
		this.session = session;
	}


	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 static long getSerialversionuid() {
		return serialVersionUID;
	}


	public String getDefaultValue() {
		return defaultValue;
	}


	public void setDefaultValue(String defaultValue) {
		this.defaultValue = defaultValue;
	}


	public List<OutstandingMessageSendReportDAO> getMessageSendReportList() {
		return messageSendReportList;
	}


	public void setMessageSendReportList(List<OutstandingMessageSendReportDAO> messageSendReportList) {
		this.messageSendReportList = messageSendReportList;
	}


	public void setSession(Map<String, Object> map) {  
	    sessionMap=(SessionMap<String, Object>)map;  
	}


	public SessionMap<String, Object> getSessionMap() {
		return sessionMap;
	}

	public void setSessionMap(SessionMap<String, Object> sessionMap) {
		this.sessionMap = sessionMap;
	}

	
	
	
	
}



