package com.kdanmobile.kdan_others_library_for_android.dialog.rateus;

import android.content.Context;
import android.content.SharedPreferences;

/**
 * Created by Wei on 2017/7/13.
 */

public class RateUsDialogHelper {
    private static final String SP_NAME = "SP_RATE_US";
    private static final String SP_HAS_CLICKED_RATE_BTN = "hasClickedRateBtn";
    private static final String SP_TRY_SHOW_COUNT = "tryCount";
    private static final int SHOW_INTERVAL = 5;

    private Context context;

    public RateUsDialogHelper(Context context) {
        this.context = context;
    }

    public boolean hasClickedRateBtn() {
        return getSP().getBoolean(SP_HAS_CLICKED_RATE_BTN, false);
    }

    public void setClickedRateBtn() {
        getSP().edit()
                .putBoolean(SP_HAS_CLICKED_RATE_BTN, true)
                .apply();
    }

    /**
     * @param rateUsDialog Build the dialog then pass to this method.
     * @return true = show, false = no show
     */
    public boolean tryToShow(RateUsDialog rateUsDialog) {
        if (hasClickedRateBtn()) return false;
        if (getTryCount() < SHOW_INTERVAL) {
            increaseTryCount();
            return false;
        }
        resetTryCount();
        showDialog(rateUsDialog);
        return true;
    }

    private void showDialog(RateUsDialog rateUsDialog) {
        Runnable onPositive = rateUsDialog.getOnPositive();
        rateUsDialog.setOnPositive(() -> {
            setClickedRateBtn();
            if (onPositive != null) onPositive.run();
        });
        rateUsDialog.show();
    }

    void resetTryCount() {
        getSP().edit()
                .putInt(SP_TRY_SHOW_COUNT, 0)
                .apply();
    }

    void increaseTryCount() {
        int count = getTryCount() + 1;
        getSP().edit()
                .putInt(SP_TRY_SHOW_COUNT, count)
                .apply();
    }

    int getTryCount() {
        return getSP().getInt(SP_TRY_SHOW_COUNT, 0);
    }

    private SharedPreferences getSP() {
        return context.getSharedPreferences(SP_NAME, Context.MODE_PRIVATE);
    }
}
