package ibase.communication;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.URL;

import javax.net.ssl.HttpsURLConnection;

import org.json.JSONArray;
import org.json.JSONObject;

import ibase.communication.utility.CommUtility;
import ibase.utility.BaseLogger;
import ibase.utility.UserInfoBean;
import ibase.webitm.ejb.DBAccessEJB;

public class WhatsAppComm {

	private DBAccessEJB dbAccess = null;

	public String sendWhatsApp(String actionInfo, String WhatsappXMLString,String receiptMobNumber, UserInfoBean userInfo, String mailXmlString,  String tranXmlString) {
		BaseLogger.log("3", null, null, " SendWhatsApp  Test 19-May-25 Ams @@####### ");
		BaseLogger.log("3", null, null, "WhatsappXMLString ==> " + WhatsappXMLString);
		BaseLogger.log("3", null, null, " ActionInfo====> " +actionInfo);
		BaseLogger.log("3", null, null, " receiptMobNumber==> " +receiptMobNumber);
		BaseLogger.log("3", null, null, " tranXmlString==> " +tranXmlString);

		try {
			
			String smsTemplateId = null;
			CommUtility commUtility = new CommUtility();
            String result = commUtility.getValue(receiptMobNumber, tranXmlString, userInfo);
            BaseLogger.log("3", null, null, "result::: [" + result + "]");
            receiptMobNumber = result;
    		BaseLogger.log("3", null, null, " receiptMobNumber==> " +receiptMobNumber);

			String templateName = getDBAccess().getDBColumnValue("MAIL_FORMAT", "TEMPLATE_NAME",
					(" FORMAT_CODE = '" + actionInfo + "' "), userInfo.getTransDB());
			
			BaseLogger.log("3", null, null, "templateName::: [" + templateName + "]");
			// Added by Amol S to get the template name for SMS and WhatsApp message, which are stored in JSON format -- Start

			if (templateName != null && templateName.trim().startsWith("{")) {
				BaseLogger.log("3", null, null, "Inside the if for whtsapp New ==>" + templateName + "]");

		        // Parse as JSON
		        JSONObject jsonObj = new JSONObject(templateName);
		        smsTemplateId = jsonObj.optString("whatsapp", templateName); 
				BaseLogger.log("3", null, null, "smsTemplateId ==>" + smsTemplateId + "]");

		    } else {
		        smsTemplateId = templateName;
		    }
			// Added by Amol S to get the template name for SMS and WhatsApp message, which are stored in JSON format -- End
			
			
			JSONObject jsonObj = new JSONObject(WhatsappXMLString);

			String endpoint = jsonObj.getString("endpoint");
			String accessToken = jsonObj.getString("token_id");
			String broadcast_name = jsonObj.getString("broadcast_name");
			JSONArray parameters = jsonObj.getJSONArray("parameters");
			
			/*
			JSONArray parameterArray = new JSONArray();
			JSONObject parameterObj = new JSONObject();
			parameterObj.put("name", "1");
			parameterObj.put("value", "123456");
			parameterArray.put(parameterObj);
			*/
			
			JSONObject jsonBodyObj = new JSONObject();
			jsonBodyObj.put("template_name", smsTemplateId);
			jsonBodyObj.put("broadcast_name", broadcast_name);
			jsonBodyObj.put("parameters", parameters);
			
			String jsonBody = jsonBodyObj.toString();
			BaseLogger.log("3", null, null, "jsonBody:: [" + jsonBody + "]");


			BaseLogger.log("3", null, null, "accessToken::: [" + accessToken + "]");
			endpoint=endpoint+receiptMobNumber;
			
			BaseLogger.log("3", null, null, "New ENDPOINT==>::: [" + endpoint + "]");


			URL url = new URL(endpoint);
		//	HttpURLConnection conn = (HttpURLConnection) url.openConnection();
			HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();

			conn.setRequestMethod("POST");
			conn.setRequestProperty("Authorization", "Bearer " + accessToken);

		//	conn.setRequestProperty("Content-Type", "application/json-patch+json");
			conn.setRequestProperty("Content-Type", "application/json");

			conn.setDoOutput(true);
		
			try (OutputStream os = conn.getOutputStream()) {
				byte[] input = jsonBody.getBytes("utf-8");
				os.write(input, 0, input.length);
			}

			int responseCode = conn.getResponseCode();
			
			BaseLogger.log("3", null, null, "WhatsApp API Response Code: " + responseCode);
			
			InputStream is;
			is = conn.getInputStream(); 
			
			BufferedReader br = new BufferedReader(new InputStreamReader(is, "UTF-8"));
			StringBuilder response = new StringBuilder();
			String line;

			while ((line = br.readLine()) != null) {
			    response.append(line);
			}
			br.close();

			if (responseCode == 200 || responseCode == 201) {
				
				BaseLogger.log("3", null, null, "WA Message sent successfully response code: [" + responseCode +"]"
						+ "Response Body ["+ response.toString() +"]");
			} else {
				BaseLogger.log("3", null, null, "Failed to send WhatsApp message. HTTP code: " + responseCode
				+ "Response Body ["+ response.toString() +"]");
			}

			conn.disconnect();

		} catch (Exception e) {
			BaseLogger.log("3", null, null, "Error sending WhatsApp message: " + e.getMessage());
			e.printStackTrace();
		}

		return WhatsappXMLString;
	}

	private DBAccessEJB getDBAccess() {
		try {
			if (dbAccess == null) {

				dbAccess = new DBAccessEJB();
			}
		}

		catch (Exception e) {
			e.printStackTrace();
		}

		return dbAccess;
	}
}
