package com.epson.mobilephone.common;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.DialogFragment;
import androidx.fragment.app.FragmentActivity;

import epson.print.R;


public class ReviewInvitationDialog extends DialogFragment {
    private static final String GOOGLE_PLAY_STORE_ID = "market://details?id=epson.print";
    private OnClickListener mOnClickListener;

    public interface OnClickListener {
        void invitationDialogClicked(boolean z);
    }

    public static ReviewInvitationDialog newInstance() {
        return new ReviewInvitationDialog();
    }

    @NonNull
    public Dialog onCreateDialog(@Nullable Bundle bundle) {
        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
        builder.setMessage(R.string.review_guidance_message).setPositiveButton(R.string.review_guidance_ok, new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialogInterface, int i) {
                startReview();
                doCallback(true);
            }
        }).setNegativeButton(R.string.review_guidance_cancel, new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialogInterface, int i) {
                doCallback(false);
            }
        });
        setCancelable(false);
        return builder.create();
    }

    private void startReview() {
        FragmentActivity activity = getActivity();
        if (activity != null) {
            PackageManager packageManager = activity.getPackageManager();
            Intent intent = new Intent("android.intent.action.VIEW");
            intent.setData(Uri.parse(GOOGLE_PLAY_STORE_ID));
            if (intent.resolveActivity(packageManager) != null) {
                activity.startActivity(intent);
            }
        }
    }

    private void doCallback(boolean z) {
        mOnClickListener.invitationDialogClicked(z);
    }

    public void onAttach(Context context) {
        super.onAttach(context);
        try {
            mOnClickListener = (OnClickListener) context;
        } catch (ClassCastException unused) {
            throw new ClassCastException(context.toString() + " must implement ReviewInvitationDialog.OnClickListener");
        }
    }

    public void onDetach() {
        super.onDetach();
        mOnClickListener = null;
    }
}
