package natch_package;

import java.io.IOException;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import javax.faces.context.FacesContext;
import javax.servlet.http.HttpSession;

@ManagedBean(name = "viewSubscriptionBean")
@ViewScoped
public class ViewSubscriptionBean implements Serializable {

    private static final long serialVersionUID = 1L;

    private SubscriptionPojo subscription;

    /* ============================================================
       MANAGE SUBSCRIPTION UI
       ============================================================ */

    private boolean manageMode = false;

    private String action;
    private String planId;
    private String nextScheduledTime;


    /* ============================================================
       CONSTRUCTOR
       ============================================================ */

    public ViewSubscriptionBean() {

        HttpSession ss = (HttpSession) FacesContext
                .getCurrentInstance()
                .getExternalContext()
                .getSession(false);

        if (ss != null) {

            subscription =
                    (SubscriptionPojo) ss.getAttribute("SubScriptionData");

        } else {

            subscription = new SubscriptionPojo();
        }
    }


    /* ============================================================
       OPEN MANAGE DROPDOWN
       ============================================================ */

    public void openManage() {

        manageMode = true;

        clearActionData();
    }


    /* ============================================================
       CLOSE MANAGE DROPDOWN
       ============================================================ */

    public void closeManage() {

        manageMode = false;

        clearActionData();
    }


    /* ============================================================
       CLEAR ACTION DATA
       ============================================================ */

    private void clearActionData() {

        action = null;
        planId = null;
        nextScheduledTime = null;
    }


    /* ============================================================
       BACK
       ============================================================ */

    public void goBack() {

        try {

            FacesContext.getCurrentInstance()
                    .getExternalContext()
                    .redirect("generateCfMandate.xhtml");

        } catch (IOException e) {

            e.printStackTrace();
        }
    }


    /* ============================================================
       TERMINAL STATUS
       ============================================================ */

    public boolean isTerminalStatus() {

        if (subscription == null ||
                subscription.getSubscription_status() == null) {

            return true;
        }

        String status =
                subscription.getSubscription_status().trim().toUpperCase();

        return Arrays.asList(
                "CANCELLED",
                "CUSTOMER_CANCELLED",
                "COMPLETED",
                "EXPIRED",
                "LINK_EXPIRED",
                "CARD_EXPIRED"
        ).contains(status);
    }


    /* ============================================================
       CANCEL ALLOWED
       ============================================================ */

    public boolean isCancelAllowed() {

        return !isTerminalStatus();
    }


    /* ============================================================
       PAUSE ALLOWED
       ============================================================ */

    public boolean isPauseAllowed() {

        if (subscription == null) {
            return false;
        }

        String status = normalize(
                subscription.getSubscription_status()
        );

        String planType = normalize(
                subscription.getPlan_type()
        );

        /*
         * Pause is allowed only when:
         *
         * ACTIVE
         * AND
         * NOT ON_DEMAND
         */

        return "ACTIVE".equals(status)
                && !"ON_DEMAND".equals(planType);
    }


    /* ============================================================
       ACTIVATE ALLOWED
       ============================================================ */

    public boolean isActivateAllowed() {

        if (subscription == null) {
            return false;
        }

        String status = normalize(
                subscription.getSubscription_status()
        );

        return "PAUSED".equals(status)
                || "ON_HOLD".equals(status);
    }


    /* ============================================================
       CHANGE PLAN ALLOWED
       ============================================================ */

    public boolean isChangePlanAllowed() {

        if (subscription == null) {
            return false;
        }

        String status = normalize(
                subscription.getSubscription_status()
        );

        String planType = normalize(
                subscription.getPlan_type()
        );

        /*
         * Change Plan is allowed only for:
         *
         * ACTIVE
         * AND
         * NOT ON_DEMAND
         */

        return "ACTIVE".equals(status)
                && !"ON_DEMAND".equals(planType);
    }


    /* ============================================================
       DYNAMIC ACTION LIST
       ============================================================ */

    public List<ActionItem> getAvailableActions() {

        List<ActionItem> actions =
                new ArrayList<ActionItem>();

        if (subscription == null ||
                isTerminalStatus()) {

            return actions;
        }


        /*
         * IMPORTANT:
         *
         * Order is:
         *
         * 1. PAUSE
         * 2. CANCEL
         * 3. ACTIVATE
         * 4. CHANGE PLAN
         *
         * This matches the UI design.
         */


        /* ========================================================
           PAUSE
           ======================================================== */

        if (isPauseAllowed()) {

            actions.add(
                    new ActionItem(
                            "PAUSE",
                            "Pause",
                            "Temporarily stop future automatic debits",
                            "warning",
                            "pi pi-pause-circle"
                    )
            );
        }


        /* ========================================================
           CANCEL
           ======================================================== */

        if (isCancelAllowed()) {

            actions.add(
                    new ActionItem(
                            "CANCEL",
                            "Cancel",
                            "Permanently cancel this subscription",
                            "danger",
                            "pi pi-ban"
                    )
            );
        }


        /* ========================================================
           ACTIVATE
           ======================================================== */

        if (isActivateAllowed()) {

            actions.add(
                    new ActionItem(
                            "ACTIVATE",
                            "Activate",
                            "Resume the subscription with a new schedule",
                            "success",
                            "pi pi-play-circle"
                    )
            );
        }


        /* ========================================================
           CHANGE PLAN
           ======================================================== */

        if (isChangePlanAllowed()) {

            actions.add(
                    new ActionItem(
                            "CHANGE_PLAN",
                            "Change Plan",
                            "Move this subscription to another plan",
                            "info",
                            "pi pi-sync"
                    )
            );
        }


        return actions;
    }


    /* ============================================================
       SELECT ACTION
       ============================================================ */

    public void selectAction(String selectedAction) {

        if (selectedAction == null ||
                selectedAction.trim().isEmpty()) {

            return;
        }

        this.action =
                selectedAction.trim().toUpperCase();


        /*
         * Clear fields which do not belong
         * to the selected action.
         */

        if (!"ACTIVATE".equals(this.action)) {

            nextScheduledTime = null;
        }

        if (!"CHANGE_PLAN".equals(this.action)) {

            planId = null;
        }
    }


    /* ============================================================
       ACTION CHANGED
       ============================================================ */

    public void actionChanged() {

        if (action == null) {
            return;
        }

        action =
                action.trim().toUpperCase();


        if (!"ACTIVATE".equals(action)) {

            nextScheduledTime = null;
        }


        if (!"CHANGE_PLAN".equals(action)) {

            planId = null;
        }
    }


    /* ============================================================
       MANAGE SUBSCRIPTION
       ============================================================ */

    public void manageSubscription() {

        /* ========================================================
           BASIC VALIDATION
           ======================================================== */

        if (subscription == null) {

            showError(
                    "Error",
                    "Subscription data is not available."
            );

            return;
        }


        String subscriptionId =
                subscription.getSubscription_id();


        if (subscriptionId == null ||
                subscriptionId.trim().isEmpty()) {

            showError(
                    "Error",
                    "Subscription ID is required."
            );

            return;
        }


        String status =
                normalize(subscription.getSubscription_status());

        String planType =
                normalize(subscription.getPlan_type());


        /* ========================================================
           TERMINAL STATUS
           ======================================================== */

        if (isTerminalStatus()) {

            showWarning(
                    "Not Allowed",
                    "This subscription cannot be modified because it is in "
                            + status
                            + " state."
            );

            return;
        }


        /* ========================================================
           ACTION REQUIRED
           ======================================================== */

        if (action == null ||
                action.trim().isEmpty()) {

            showWarning(
                    "Select Action",
                    "Please select an action."
            );

            return;
        }


        action =
                action.trim().toUpperCase();


        /* ========================================================
           CANCEL
           ======================================================== */

        if ("CANCEL".equals(action)) {

            /*
             * CANCEL is allowed for every
             * non-terminal subscription.
             */

        }


        /* ========================================================
           PAUSE
           ======================================================== */

        else if ("PAUSE".equals(action)) {

            if (!"ACTIVE".equals(status)) {

                showWarning(
                        "Not Allowed",
                        "Pause is only allowed for ACTIVE subscriptions."
                );

                return;
            }


            if ("ON_DEMAND".equals(planType)) {

                showError(
                        "Not Allowed",
                        "Pause is not supported for ON_DEMAND subscriptions."
                );

                return;
            }
        }


        /* ========================================================
           ACTIVATE
           ======================================================== */

        else if ("ACTIVATE".equals(action)) {

            if (!"PAUSED".equals(status)
                    && !"ON_HOLD".equals(status)) {

                showWarning(
                        "Not Allowed",
                        "Activate is only allowed for PAUSED or ON_HOLD subscriptions."
                );

                return;
            }


            if (nextScheduledTime == null
                    || nextScheduledTime.trim().isEmpty()) {

                showError(
                        "Required",
                        "Please enter the next scheduled time."
                );

                return;
            }
        }


        /* ========================================================
           CHANGE PLAN
           ======================================================== */

        else if ("CHANGE_PLAN".equals(action)) {

            if (!"ACTIVE".equals(status)) {

                showWarning(
                        "Not Allowed",
                        "Change Plan is only allowed for ACTIVE subscriptions."
                );

                return;
            }


            if ("ON_DEMAND".equals(planType)) {

                showError(
                        "Not Allowed",
                        "Change Plan is not supported for ON_DEMAND subscriptions."
                );

                return;
            }


            if (planId == null ||
                    planId.trim().isEmpty()) {

                showError(
                        "Required",
                        "Please enter the new Plan ID."
                );

                return;
            }
        }


        /* ========================================================
           INVALID ACTION
           ======================================================== */

        else {

            showError(
                    "Invalid Action",
                    "Invalid subscription action: " + action
            );

            return;
        }


        /* ========================================================
           CALL DAO
           ======================================================== */

        SubscriptionDAO dao =
                new SubscriptionDAO();

        SubscriptionPojo result =
                dao.MANAGEPLAN(
                        action,
                        subscriptionId,
                        planId,
                        nextScheduledTime
                );


        /* ========================================================
           SUCCESS
           ======================================================== */

        if (result != null &&
                result.isDataFetch()) {

            /*
             * If DAO returned updated status,
             * update the current page immediately.
             */

            if (result.getSubscription_status() != null
                    && !result.getSubscription_status().trim().isEmpty()) {

                subscription.setSubscription_status(
                        result.getSubscription_status()
                );
            }


            /*
             * Success message
             */

            FacesContext.getCurrentInstance().addMessage(
                    null,
                    new FacesMessage(
                            FacesMessage.SEVERITY_INFO,
                            "Success",
                            "Subscription "
                                    + action
                                    + " completed successfully."
                    )
            );


            /*
             * Clear selected action after success.
             */

            clearActionData();


            /*
             * Keep dropdown open.
             *
             * If you want it to automatically close
             * after successful action, change this to:
             *
             * manageMode = false;
             */

            manageMode = true;

        }


        /* ========================================================
           FAILURE
           ======================================================== */

        else {

            String message =
                    "Unable to process subscription action.";

            if (result != null &&
                    result.getMessage() != null &&
                    !result.getMessage().trim().isEmpty()) {

                message = result.getMessage();
            }


            showError(
                    "Failed",
                    message
            );
        }
    }


    /* ============================================================
       NORMALIZE STRING
       ============================================================ */

    private String normalize(String value) {

        if (value == null) {
            return "";
        }

        return value.trim().toUpperCase();
    }


    /* ============================================================
       ERROR MESSAGE
       ============================================================ */

    private void showError(
            String title,
            String message) {

        FacesContext.getCurrentInstance().addMessage(
                null,
                new FacesMessage(
                        FacesMessage.SEVERITY_ERROR,
                        title,
                        message
                )
        );
    }


    /* ============================================================
       WARNING MESSAGE
       ============================================================ */

    private void showWarning(
            String title,
            String message) {

        FacesContext.getCurrentInstance().addMessage(
                null,
                new FacesMessage(
                        FacesMessage.SEVERITY_WARN,
                        title,
                        message
                )
        );
    }


    /* ============================================================
       GET SUBSCRIPTION
       ============================================================ */

    public SubscriptionPojo getSubscription() {

        return subscription;
    }


    public void setSubscription(
            SubscriptionPojo subscription) {

        this.subscription = subscription;
    }


    /* ============================================================
       MANAGE MODE
       ============================================================ */

    public boolean isManageMode() {

        return manageMode;
    }


    public void setManageMode(
            boolean manageMode) {

        this.manageMode = manageMode;
    }


    /* ============================================================
       ACTION
       ============================================================ */

    public String getAction() {

        return action;
    }


    public void setAction(String action) {

        this.action = action;

        if (action != null) {

            this.action =
                    action.trim().toUpperCase();
        }
    }


    /* ============================================================
       PLAN ID
       ============================================================ */

    public String getPlanId() {

        return planId;
    }


    public void setPlanId(String planId) {

        this.planId = planId;
    }


    /* ============================================================
       NEXT SCHEDULED TIME
       ============================================================ */

    public String getNextScheduledTime() {

        return nextScheduledTime;
    }


    public void setNextScheduledTime(
            String nextScheduledTime) {

        this.nextScheduledTime =
                nextScheduledTime;
    }


    /* ============================================================
       ACTION ITEM
       ============================================================ */

    public static class ActionItem
            implements Serializable {

        private static final long serialVersionUID = 1L;

        private String value;
        private String label;
        private String description;
        private String style;
        private String icon;


        public ActionItem(
                String value,
                String label,
                String description,
                String style,
                String icon) {

            this.value = value;
            this.label = label;
            this.description = description;
            this.style = style;
            this.icon = icon;
        }


        public String getValue() {

            return value;
        }


        public void setValue(String value) {

            this.value = value;
        }


        public String getLabel() {

            return label;
        }


        public void setLabel(String label) {

            this.label = label;
        }


        public String getDescription() {

            return description;
        }


        public void setDescription(
                String description) {

            this.description = description;
        }


        public String getStyle() {

            return style;
        }


        public void setStyle(String style) {

            this.style = style;
        }


        public String getIcon() {

            return icon;
        }


        public void setIcon(String icon) {

            this.icon = icon;
        }
    }
}