package cashfree;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Map;
import java.util.UUID;

import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;

import org.primefaces.json.JSONArray;
import org.primefaces.json.JSONObject;

import natch_package.SubscriptionSaver;

public class CashfreeSubscriptionService{

	private SubscriptionResponse sendSubscriptionRequest(CreateSubscriptionRequest subscriptionRequest) {

	    HttpURLConnection connection = null;

	    try {
	        String apiUrl = "https://sandbox.cashfree.com/pg/subscriptions";

	        JSONObject jsonBody = new JSONObject();

	        jsonBody.put("subscription_id",subscriptionRequest.getSubscription_id());

	        // CUSTOMER DETAILS
	        JSONObject customerDetails = new JSONObject();

	        customerDetails.put("customer_name",subscriptionRequest.getCustomer_name()); 
            customerDetails.put("customer_email",subscriptionRequest.getCustomer_email());
            customerDetails.put("customer_phone",subscriptionRequest.getCustomer_phone());
	        customerDetails.put("customer_bank_account_holder_name",subscriptionRequest.getCustomer_bank_account_holder_name());
	        customerDetails.put("customer_bank_account_number",subscriptionRequest.getCustomer_bank_account_number());
	        customerDetails.put("customer_bank_ifsc",subscriptionRequest.getCustomer_bank_ifsc());
	        customerDetails.put("customer_bank_code",subscriptionRequest.getCustomer_bank_code());
	        customerDetails.put("customer_bank_account_type",subscriptionRequest.getCustomer_bank_account_type());

	        jsonBody.put("customer_details", customerDetails);


	        // PLAN DETAILS
	        JSONObject planDetails = new JSONObject();

	        if (subscriptionRequest.getPlan_id() != null && !subscriptionRequest.getPlan_id().trim().isEmpty()) {

	            planDetails.put("plan_id", subscriptionRequest.getPlan_id());

	        } else {

	            planDetails.put("plan_name", subscriptionRequest.getPlan_name());
	            planDetails.put("plan_type", subscriptionRequest.getPlan_type());
	            planDetails.put("plan_amount",subscriptionRequest.getPlan_amount());
	            planDetails.put("plan_max_amount",subscriptionRequest.getPlan_max_amount());
	            planDetails.put("plan_max_cycles", subscriptionRequest.getPlan_max_cycles());
	            planDetails.put("plan_intervals",subscriptionRequest.getPlan_intervals());
	            planDetails.put("plan_currency", subscriptionRequest.getPlan_currency());
	            planDetails.put("plan_interval_type",subscriptionRequest.getPlan_interval_type());

	            if (subscriptionRequest.getPlan_note() != null && !subscriptionRequest.getPlan_note().trim().isEmpty()) {

	                planDetails.put("plan_note", subscriptionRequest.getPlan_note());
	            }
	        }

	        jsonBody.put("plan_details", planDetails);


	        // AUTHORIZATION DETAILS
	        JSONObject authorizationDetails = new JSONObject();

	        authorizationDetails.put("authorization_amount", subscriptionRequest.getAuthorization_amount());
	        authorizationDetails.put("authorization_amount_refund",subscriptionRequest.isAuthorization_amount_refund());

	        JSONArray paymentMethods = new JSONArray();

	        if (subscriptionRequest.getPayment_methods() != null) {

	            for (String method : subscriptionRequest.getPayment_methods()) {
	                paymentMethods.put(method);
	            }
	        }

	        authorizationDetails.put("payment_methods", paymentMethods);

	        jsonBody.put("authorization_details", authorizationDetails);


	        // SUBSCRIPTION META
	        JSONObject subscriptionMeta = new JSONObject();

	        if (subscriptionRequest.getReturn_url() != null) {
	            subscriptionMeta.put("return_url", subscriptionRequest.getReturn_url());
	        }

	        if (subscriptionRequest.getNotification_channel() != null) {

	            JSONArray channels = new JSONArray();
	            for (String channel : subscriptionRequest.getNotification_channel()) {

	                channels.put(channel);
	            }

	            subscriptionMeta.put("notification_channel", channels);
	        }

	        if (subscriptionRequest.getSession_id_expiry() != null) {
	            subscriptionMeta.put("session_id_expiry",subscriptionRequest.getSession_id_expiry());
	        }

	        jsonBody.put("subscription_meta", subscriptionMeta);


	        // SUBSCRIPTION TIMING
	        if (subscriptionRequest.getSubscription_expiry_time() != null) {
	            jsonBody.put("subscription_expiry_time",subscriptionRequest.getSubscription_expiry_time());
	        }
	        if (subscriptionRequest.getSubscription_first_charge_time() != null) {
	            jsonBody.put("subscription_first_charge_time",subscriptionRequest.getSubscription_first_charge_time());
	        }

	        // SUBSCRIPTION NOTE
	        if (subscriptionRequest.getSubscription_note() != null   && !subscriptionRequest.getSubscription_note().trim().isEmpty()) {
	            jsonBody.put("subscription_note", subscriptionRequest.getSubscription_note());
	        }

	        // SUBSCRIPTION TAGS
	        if (subscriptionRequest.getSubscription_tags() != null) {

	            JSONObject subscriptionTags = new JSONObject(subscriptionRequest.getSubscription_tags());
	            jsonBody.put("subscription_tags", subscriptionTags);
	        }


	        // CONNECTION
	        URL url = new URL(
	        	    CashfreeApiUtil.getSandboxSubscriptionUrl()
	        	);

	        	 connection =
	        	    (HttpURLConnection) url.openConnection();

	        	connection.setRequestMethod("POST");
	        	connection.setDoOutput(true);

	        	CashfreeApiUtil.setHeaders(connection);

	        // REQUEST
	        OutputStream os = connection.getOutputStream();

	        os.write(
	                jsonBody.toString()
	                        .getBytes("UTF-8")
	        );

	        os.flush();
	        os.close();


	        // RESPONSE
	        int responseCode = connection.getResponseCode();

	        String responseBody;

	        if (responseCode >= 200 && responseCode < 300) {

	            responseBody = readStream(
	                    connection.getInputStream());

	        } else {

	            responseBody = readStream(
	                    connection.getErrorStream());
	        }


	        // JSON RESPONSE
	        JSONObject responseJson =new JSONObject(responseBody);

	        SubscriptionResponse response = new SubscriptionResponse();

	        response.setCf_subscription_id( responseJson.optString("cf_subscription_id",null));
	        response.setSubscription_id( responseJson.optString( "subscription_id",null));
	        response.setSubscription_status(responseJson.optString("subscription_status", null));

	        response.setSubscription_expiry_time(
	                responseJson.optString(
	                        "subscription_expiry_time",
	                        null));

	        response.setSubscription_first_charge_time(
	                responseJson.optString(
	                        "subscription_first_charge_time",
	                        null));

	        response.setSubscription_session_id(
	                responseJson.optString(
	                        "subscription_session_id",
	                        null));

	        response.setSubscription_note(
	                responseJson.optString(
	                        "subscription_note",
	                        null));


	        // ERROR FIELDS
	        response.setMessage(
	                responseJson.optString(
	                        "message",
	                        null));

	        response.setHelp(
	                responseJson.optString(
	                        "help",
	                        null));

	        response.setCode(
	                responseJson.optString(
	                        "code",
	                        null));

	        response.setType(
	                responseJson.optString(
	                        "type",
	                        null));


	        // CUSTOMER
	        JSONObject customer =
	                responseJson.optJSONObject(
	                        "customer_details");

	        if (customer != null) {

	            response.setCustomer_name(
	                    customer.optString(
	                            "customer_name",
	                            null));

	            response.setCustomer_email(
	                    customer.optString(
	                            "customer_email",
	                            null));

	            response.setCustomer_phone(
	                    customer.optString(
	                            "customer_phone",
	                            null));

	            response.setCustomer_bank_account_holder_name(
	                    customer.optString(
	                            "customer_bank_account_holder_name",
	                            null));

	            response.setCustomer_bank_account_number(
	                    customer.optString(
	                            "customer_bank_account_number",
	                            null));

	            response.setCustomer_bank_ifsc(
	                    customer.optString(
	                            "customer_bank_ifsc",
	                            null));

	            response.setCustomer_bank_code(
	                    customer.optString(
	                            "customer_bank_code",
	                            null));

	            response.setCustomer_bank_account_type(
	                    customer.optString(
	                            "customer_bank_account_type",
	                            null));
	        }


	        // PLAN
	        JSONObject plan =
	                responseJson.optJSONObject(
	                        "plan_details");

	        if (plan != null) {

	            response.setPlan_id(
	                    plan.optString(
	                            "plan_id",
	                            null));

	            response.setPlan_name(
	                    plan.optString(
	                            "plan_name",
	                            null));

	            response.setPlan_type(
	                    plan.optString(
	                            "plan_type",
	                            null));

	            response.setPlan_max_cycles(
	                    plan.optInt(
	                            "plan_max_cycles",
	                            0));

	            response.setPlan_recurring_amount(
	                    plan.optDouble(
	                            "plan_recurring_amount",
	                            0));

	            response.setPlan_max_amount(
	                    plan.optDouble(
	                            "plan_max_amount",
	                            0));

	            response.setPlan_interval_type(
	                    plan.optString(
	                            "plan_interval_type",
	                            null));

	            response.setPlan_intervals(
	                    plan.optInt(
	                            "plan_intervals",
	                            0));

	            response.setPlan_currency(
	                    plan.optString(
	                            "plan_currency",
	                            null));

	            response.setPlan_note(
	                    plan.optString(
	                            "plan_note",
	                            null));

	            response.setPlan_status(
	                    plan.optString(
	                            "plan_status",
	                            null));
	        }


	        // AUTHORISATION
	        JSONObject authorisation =
	                responseJson.optJSONObject(
	                        "authorisation_details");

	        if (authorisation != null) {

	            response.setAuthorization_amount(
	                    authorisation.optDouble(
	                            "authorization_amount",
	                            0));

	            response.setAuthorization_amount_refund(
	                    authorisation.optBoolean(
	                            "authorization_amount_refund",
	                            false));

	            response.setAuthorization_reference(
	                    authorisation.optString(
	                            "authorization_reference",
	                            null));

	            response.setAuthorization_time(
	                    authorisation.optString(
	                            "authorization_time",
	                            null));

	            response.setAuthorization_status(
	                    authorisation.optString(
	                            "authorization_status",
	                            null));

	            response.setPayment_id(
	                    authorisation.optString(
	                            "payment_id",
	                            null));

	            response.setPayment_group(
	                    authorisation.optString(
	                            "payment_group",
	                            null));
	        }


	        // SCHEDULE
	        response.setNext_schedule_date(
	                responseJson.optString(
	                        "next_schedule_date",
	                        null));


	        // META
	        JSONObject meta =
	                responseJson.optJSONObject(
	                        "subscription_meta");

	        if (meta != null) {

	            response.setReturn_url(
	                    meta.optString(
	                            "return_url",
	                            null));
	        }


	        // TAGS
	        JSONObject tags =
	                responseJson.optJSONObject(
	                        "subscription_tags");

	        if (tags != null) {

	            Map<String, String> tagMap =
	                    new java.util.HashMap<String, String>();

	            for (String key : tags.keySet()) {
	                tagMap.put(
	                        key,
	                        tags.optString(key, null));
	            }

	            response.setSubscription_tags(tagMap);
	        }


	        return response;

	    } catch (Exception e) {

	        return null;

	    } finally {

	        if (connection != null) {
	            connection.disconnect();
	        }
	    }
	}
	 
	 public String generateUniqueSubscriptionId() {
	        String timestamp = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMdd_HHmmss"));
	        String randomPart = UUID.randomUUID().toString().replaceAll("-", "").substring(0, 8);
	        String subscriptionId = "SUB_" + timestamp + "_" + randomPart;

	        if (subscriptionId.length() > 40) {
	            subscriptionId = subscriptionId.substring(0, 40);
	        }

	        return subscriptionId;
	    }
	 
	 private String readStream(InputStream inputStream) throws IOException {
	        BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
	        StringBuilder response = new StringBuilder();
	        String line;
	        while ((line = reader.readLine()) != null) {
	            response.append(line);
	        }
	        reader.close();
	        return response.toString();
	    }
	
	
}
