package tech.starwin.utils.ui_utils;


import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.ContextWrapper;
import android.content.DialogInterface;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.LayoutRes;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.content.ContextCompat;
import android.text.InputType;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.qmuiteam.qmui.util.QMUIDisplayHelper;
import com.qmuiteam.qmui.widget.dialog.QMUIDialog;
import com.qmuiteam.qmui.widget.dialog.QMUIDialogAction;
import com.qmuiteam.qmui.widget.dialog.QMUITipDialog;
import com.qmuiteam.qmui.widget.popup.QMUIPopup;

import java.util.concurrent.TimeUnit;

import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Consumer;
import tech.starwin.R;
import tech.starwin.base.RecyclerViewHolder;

import static android.view.ViewGroup.LayoutParams.WRAP_CONTENT;


/**
 * Created by SiKang on 2018/2/6.
 * 快速创建常用Dialog
 */

public class DialogFactory {

    /**
     * 创建一个半透明背景带有Icon的Dialog （Loading、Error等)
     */
    public static Dialog createTipDialog(Context context, @QMUITipDialog.Builder.IconType int mode, String tipWord) {
        return new QMUITipDialog.Builder(context)
                .setIconType(mode)
                .setTipWord(tipWord)
                .create();
    }

    /**
     * 创建一个带有文本提示的对话框
     */
    public static void showMessageDialog(Context context, String msg) {
        createMessageDialog(context, "Tip", msg, "ok", null).show();
    }

    public static Dialog createMessageDialog(Context context, String title, String message, String btnText) {
        return createMessageDialog(context, title, message, btnText, null);
    }

    public static Dialog createMessageDialog(Context context, String title, String message, String btnText, QMUIDialogAction.ActionListener listener) {
        if (listener == null) {
            listener = new QMUIDialogAction.ActionListener() {
                @Override
                public void onClick(QMUIDialog dialog, int index) {
                    dialog.dismiss();
                }
            };
        }
        return new QMUIDialog.MessageDialogBuilder(context)
                .setTitle(title)
                .setMessage(message)
                .addAction(btnText, listener)
                .create();
    }

    /**
     * 创建一个带有文本提示和两个含义相对按钮的对话框
     */
    public static Dialog createYesOrNoDialog(Context context, String msg, final OnYesOrNoListener onYesOrNoListener) {
        return createYesOrNoDialog(context, "Tip", msg, context.getString(R.string.text_sure), context.getString(R.string.text_cancel), onYesOrNoListener);
    }

    public static Dialog createYesOrNoDialog(Context context, String title, String msg, String yesBtnText, String noBtnText, final OnYesOrNoListener onYesOrNoListener) {
        final Dialog dialog = new QMUIDialog.MessageDialogBuilder(context)
                .setTitle(title)
                .setMessage(msg)
                .addAction(0, noBtnText, QMUIDialogAction.ACTION_PROP_NEGATIVE, new QMUIDialogAction.ActionListener() {
                    @Override
                    public void onClick(QMUIDialog dialog, int index) {
                        onYesOrNoListener.onClick(dialog, false);
                    }
                })
                .addAction(yesBtnText, new QMUIDialogAction.ActionListener() {
                    @Override
                    public void onClick(QMUIDialog dialog, int index) {
                        onYesOrNoListener.onClick(dialog, true);
                    }
                })
                .create();
        return dialog;
    }

    /**
     * 创建一个带输入框的对话框
     */
    public static Dialog createInputDialog(Context context, String title, String placeholder, final String btnText, final OnInputActionListener listener) {
        final QMUIDialog.EditTextDialogBuilder builder = new QMUIDialog.EditTextDialogBuilder(context);
        return builder.setTitle(title)
                .setTitle(title)
                .setPlaceholder(placeholder)
                .setInputType(InputType.TYPE_CLASS_TEXT)
                .addAction("cancel", new QMUIDialogAction.ActionListener() {
                    @Override
                    public void onClick(QMUIDialog dialog, int index) {
                        dialog.dismiss();
                    }
                })
                .addAction(btnText, new QMUIDialogAction.ActionListener() {
                    @Override
                    public void onClick(QMUIDialog dialog, int index) {
                        listener.onClick(dialog, builder.getEditText());
                    }
                })
                .create();
    }

    /**
     * 创建菜单类型对话框
     */
    public static Dialog createMenuDialog(Context context, String[] items, DialogInterface.OnClickListener listener) {
        return new QMUIDialog.MenuDialogBuilder(context)
                .addItems(items, listener)
                .create();
    }


    /**
     * 创建一个单选菜单
     */
    public static Dialog createSingleChoiceDialog(Context context, String[] items, int checkedIndex, DialogInterface.OnClickListener listene) {
        return new QMUIDialog.CheckableDialogBuilder(context)
                .setCheckedIndex(checkedIndex)
                .addItems(items, listene)
                .create();
    }


    /**
     * 创建一个多选对话框
     */
    public static Dialog createMultiChoiceDialog(Context context, String btnText, String[] items, int[] checkedItems, final OnMultiChoicectionListener listene) {
        final QMUIDialog.MultiCheckableDialogBuilder builder = new QMUIDialog.MultiCheckableDialogBuilder(context)
                .setCheckedItems(checkedItems)
                .addItems(items, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {

                    }
                });
        builder.addAction("cancel", new QMUIDialogAction.ActionListener() {
            @Override
            public void onClick(QMUIDialog dialog, int index) {
                dialog.dismiss();
            }
        }).addAction(btnText, new QMUIDialogAction.ActionListener() {
            @Override
            public void onClick(QMUIDialog dialog, int index) {
                listene.onClick(dialog, builder.getCheckedItemIndexes());
            }
        });
        return builder.create();
    }


    /**
     * 创建一个自定义的Dialog
     */
    public static Dialog createCustomDialog(Context context, @LayoutRes int layout, OnViewCreatedListener listener) {
        View view = LayoutInflater.from(context).inflate(layout, null);
        Dialog dialog = new CustomDialog(context, view);
        listener.onCreatedView(dialog, new RecyclerViewHolder(view));
        return dialog;
    }


    /**
     * 显示一个对话框，并在计时结束后dismiss
     */
    @SuppressLint("CheckResult")
    public static void showTiming(final Dialog dialog, int time) {
        dialog.show();
        Observable.just(true)
                .delay(time, TimeUnit.MILLISECONDS)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<Object>() {
                    @Override
                    public void accept(Object aBoolean) throws Exception {
                        dialog.dismiss();
                    }
                });
    }


    /**
     * 创建一个popup
     */
    public static QMUIPopup createBottomPopup(Context context, String text) {
        return createPopup(context, text, QMUIPopup.DIRECTION_BOTTOM);
    }

    public static QMUIPopup createTopPopup(Context context, String text) {
        return createPopup(context, text, QMUIPopup.DIRECTION_TOP);
    }

    public static QMUIPopup createPopup(Context context, String text, int direction) {
        QMUIPopup popup = new QMUIPopup(context, QMUIPopup.DIRECTION_NONE);

        TextView textView = new TextView(context);
        textView.setLayoutParams(popup.generateLayoutParam(WRAP_CONTENT, WRAP_CONTENT));
        textView.setLineSpacing(QMUIDisplayHelper.dp2px(context, 4), 1.0f);
        int padding = QMUIDisplayHelper.dp2px(context, 20);
        textView.setPadding(padding, padding, padding, padding);
        textView.setText(text);
        textView.setTextColor(ContextCompat.getColor(context, R.color.qmui_config_color_gray_6));

        popup.setContentView(textView);
        popup.setAnimStyle(QMUIPopup.ANIM_GROW_FROM_CENTER);
        popup.setPreferredDirection(direction);
        return popup;
    }


    public interface OnInputActionListener {
        void onClick(QMUIDialog dialog, EditText editText);
    }

    public interface OnMultiChoicectionListener {
        void onClick(QMUIDialog dialog, int[] checkedItemIndexes);
    }

    public interface OnYesOrNoListener {
        void onClick(Dialog dialog, boolean isAgree);
    }

    public interface OnViewCreatedListener {
        void onCreatedView(Dialog dialog, RecyclerViewHolder viewHolder);
    }

    public static void dismiss(Dialog dialog) {
        if (dialog != null) {
            Context context = ((ContextWrapper) dialog.getContext()).getBaseContext();
            if (context instanceof Activity) {
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
                    if (!((Activity) context).isFinishing() && !((Activity) context).isDestroyed())
                        dialog.dismiss();
                } else
                    dialog.dismiss();
            } else
                dialog.dismiss();
        }
    }

    public static class CustomDialog extends Dialog {
        View view;

        public CustomDialog(@NonNull Context context, View view) {
            super(context);
            this.view = view;
        }

        @Override
        public void show() {
            super.show();
            setContentView(view);
        }
    }

}
