package com.kdanmobile.kdan_others_library_for_android.dialog;

import android.content.Context;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.TextView;

import com.kdanmobile.kdan_others_library_for_android.R;

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

public class UpdateLatestAppDialog {
    private Context context;
    private String appName;
    private Runnable positiveL;
    private Runnable negativeL;
    private Runnable cancelL;

    private UpdateLatestAppDialog() {}

    public void show() {
        View v = createView();
        new AlertDialog.Builder(context)
                .setView(v)
                .setPositiveButton(R.string.update_latest_app_dialog_positive_btn, ((di, i) -> {
                    if (positiveL != null) positiveL.run();
                }))
                .setNegativeButton(R.string.update_latest_app_dialog_negative_btn, (((di, i) -> {
                    if (negativeL != null) negativeL.run();
                })))
                .setOnCancelListener(di -> {
                    if (cancelL != null) cancelL.run();
                })
                .show();
    }

    @NonNull
    private View createView() {
        View v = LayoutInflater.from(context).inflate(R.layout.dialog_update_latest_app, null);
        String s = context.getString(R.string.update_latest_app_dialog_content, appName);
        TextView content = (TextView) v.findViewById(R.id.tv_update_latest_version_dialog_content);
        content.setText(s);
        return v;
    }

    public static class Builder {
        private Context context;
        private String appName;
        private Runnable positiveL;
        private Runnable negativeL;
        private Runnable cancelL;

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

        public Builder setAppName(String appName) {
            this.appName = appName;
            return this;
        }

        public Builder setAppName(int resId) {
            this.appName = context.getString(resId);
            return this;
        }

        public Builder setOnPositive(Runnable l) {
            positiveL = l;
            return this;
        }

        public Builder setOnNegative(Runnable l) {
            negativeL = l;
            return this;
        }

        public Builder setOnCancel(Runnable l) {
            cancelL = l;
            return this;
        }

        public UpdateLatestAppDialog build() {
            UpdateLatestAppDialog d = new UpdateLatestAppDialog();
            d.context = context;
            d.appName = appName;
            d.positiveL = positiveL;
            d.negativeL = negativeL;
            d.cancelL = cancelL;
            return d;
        }

        public void show() {
            build().show();
        }
    }
}
