package co.pixelbeard.theanfieldwrap.freeSubscription;

import android.content.Context;
import android.os.Bundle;
import android.text.Html;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import butterknife.BindView;
import butterknife.ButterKnife;
import co.pixelbeard.theanfieldwrap.R;
import co.pixelbeard.theanfieldwrap.billing.BillingConstants;
import co.pixelbeard.theanfieldwrap.utils.BaseFragment;
import co.pixelbeard.theanfieldwrap.utils.BulletView;

public class SubscriptionPackageFragment extends BaseFragment {

    @BindView(R.id.planTextView)
    TextView planTextView;
    @BindView(R.id.priceTV)
    TextView priceTV;
    @BindView(R.id.descriptionTV1)
    BulletView descriptionTV1;
    @BindView(R.id.descriptionTV2)
    BulletView descriptionTV2;
    @BindView(R.id.descriptionTV3)
    BulletView descriptionTV3;
    @BindView(R.id.descriptionTV4)
    BulletView descriptionTV4;
    @BindView(R.id.topIconView)
    ImageView topIconView;
    @BindView(R.id.audioImageView)
    ImageView audioImageView;
    @BindView(R.id.videoImageView)
    ImageView videoImageView;
    @BindView(R.id.activeSubscriptionBtn)
    TextView activeSubscriptionBtn;

    private String subscriptionType;
    private String planName;
    private String planType;
    private int planDuration;

    private SubscriptionActivity mListener;

    private SubscriptionPackageFragment() {
    }

    @Override
    public void onAttach(@NonNull Context context) {
        super.onAttach(context);
        mListener = (SubscriptionActivity) context;
    }

    public static SubscriptionPackageFragment getInstance(SubscriptionModel model) {
        SubscriptionPackageFragment fragment = new SubscriptionPackageFragment();
        Bundle mBundle = new Bundle();
        mBundle.putParcelable("subscription", model);
        fragment.setArguments(mBundle);
        return fragment;
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View mView = inflater.inflate(R.layout.viewpager_subscription, container, false);
        ButterKnife.bind(this, mView);
        return mView;
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        SubscriptionModel model = getArguments().getParcelable("subscription");
        setUI(model);
        handleClick();
    }

    private void handleClick() {
        activeSubscriptionBtn.setOnClickListener(view -> {
            mListener.purchaseSubscription(planName, planType, planDuration);
        });
    }

    private void setUI(SubscriptionModel model) {
        subscriptionType = model.getSubscriptionType();
        planType = model.getPlanType();
        planName = model.getPlanName();
        planDuration = getDaysFromTreeTrail(model.getDuration());

        planTextView.setText(model.getTitle());
        descriptionTV2.setText(getString(R.string.premium_description2));
        descriptionTV3.setText(getString(R.string.premium_description3));
        descriptionTV4.setText(getString(R.string.premium_description4));
        String buttonText;
        if (model.getPlanType().equals(BillingConstants.FREE) && planDuration != 0) {
            buttonText = getString(R.string.subscription_interval_text, bottomPayText(planDuration));
        } else {
            planType = BillingConstants.PAID;
            planDuration = BillingConstants.MONTH;
            buttonText = getString(R.string.subscription_buy_for_text, model.getPlanAmount());
        }
        activeSubscriptionBtn.setText(buttonText);
        priceTV.setText(model.getPlanAmount());
        if (subscriptionType.equals("9")) {
            descriptionTV1.setText(Html.fromHtml(getString(R.string.premium_description1)));
            topIconView.setImageResource(R.drawable.crown);
        } else if (subscriptionType.equals("7")) { // video type
            descriptionTV1.setText(Html.fromHtml(getString(R.string.premium_video_description1)));
            topIconView.setImageResource(R.drawable.video_active);
            audioImageView.setImageResource(R.drawable.pod_inactive);
            audioImageView.setBackgroundColor(getResources().getColor(R.color.subscription_deactivate));
        } else {
            descriptionTV1.setText(Html.fromHtml(getString(R.string.premium_audio_description1)));
            topIconView.setImageResource(R.drawable.pod_active);
            videoImageView.setBackgroundColor(getResources().getColor(R.color.subscription_deactivate));
            videoImageView.setImageResource(R.drawable.video_inactive);
        }
    }

    /**
     * Split the free trial period string and get result in days
     * sample string from play store: P1W1D | P1W | P1D
     *
     * @param freeTrailPeriod
     * @return
     */
    private int getDaysFromTreeTrail(String freeTrailPeriod) {
        if (freeTrailPeriod.isEmpty()) {
            return 0;
        }
        if (freeTrailPeriod.contains("W")) {
            String weekString = freeTrailPeriod.substring(1, freeTrailPeriod.indexOf("W"));
            int weekDays = Integer.parseInt(weekString) * 7;
            String dayString = "0";
            if (freeTrailPeriod.contains("D")) {
                dayString = freeTrailPeriod.substring(freeTrailPeriod.indexOf("W") + 1, freeTrailPeriod.indexOf("D"));
            }
            return weekDays + Integer.parseInt(dayString);
        } else {
            String dayString = freeTrailPeriod.substring(freeTrailPeriod.indexOf("P") + 1, freeTrailPeriod.indexOf("D"));
            return Integer.parseInt(dayString);
        }
    }

    private String bottomPayText(int totalDays) {
        String finalText = "";
        int divisor = 30; // total days in month

        int month = totalDays / divisor;
        int days = totalDays % divisor;
        if (month != 0) {
            if (month == 1) {
                finalText = month + " Month ";
            } else {
                finalText = month + " Months ";
            }
        }
        if (days != 0) {
            finalText = finalText + days + " Days";
        }
        return finalText;
    }
}
