package tech.starwin.utils.ui_utils;


import android.app.Activity;
import android.app.Instrumentation;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.support.annotation.DrawableRes;
import android.support.annotation.IdRes;
import android.support.annotation.NonNull;
import android.support.annotation.StringRes;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.DisplayMetrics;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.Toast;

import com.qmuiteam.qmui.widget.QMUITabSegment;
import com.qmuiteam.qmui.widget.grouplist.QMUICommonListItemView;
import com.qmuiteam.qmui.widget.grouplist.QMUIGroupListView;

import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.schedulers.Schedulers;
import tech.starwin.utils.BitmapUtils;


/**
 * Created by SiKang on 2018/9/14.
 */
public class UIHelper {

    /**
     * 为View添加ClickListener
     */
    public static <T extends View.OnClickListener> void bindClickListener(T listener, View... views) {
        if (views.length == 0 || listener == null) {
            return;
        }
        for (View view : views) {
            view.setOnClickListener(listener);
        }
    }

    /**
     * 为View添加ClickListener
     */
    public static <T extends View.OnClickListener> void bindClickListener(ViewGroup viewGroup, T listener, @IdRes int... idSet) {
        if (idSet.length == 0 && listener == null) {
            return;
        }
        for (int id : idSet) {
            View view = viewGroup.findViewById(id);
            if (view != null) {
                view.setOnClickListener(listener);
            }
        }

    }

    /**
     * 按默认配置初始化RecylerView 并绑定Adapter
     */
    public static void bindAdapter(Context context, RecyclerView recyclerView, RecyclerView.Adapter adapter) {
        recyclerView.setLayoutManager(new LinearLayoutManager(context));
        recyclerView.setAdapter(adapter);
        recyclerView.setItemAnimator(new DefaultItemAnimator());
    }


    /**
     * 显示Toast
     */
    public static void showToast(@NonNull Context context, @StringRes int str) {
        showToast(context, context.getString(str), Toast.LENGTH_SHORT);
    }

    public static void showToast(@NonNull Context context, String msg) {
        showToast(context, msg, Toast.LENGTH_SHORT);
    }

    public static void showToast(@NonNull Context context, String msg, int time) {
        Toast.makeText(context, msg, time).show();
    }


    /**
     * 打开软键盘
     *
     * @param mEditText 输入框
     */
    public static void openKeybord(EditText mEditText) {
        if (!isKeyboardOpened(mEditText)) {
            InputMethodManager imm = (InputMethodManager) mEditText.getContext()
                    .getSystemService(Context.INPUT_METHOD_SERVICE);
            imm.showSoftInput(mEditText, InputMethodManager.RESULT_SHOWN);
            imm.toggleSoftInput(InputMethodManager.SHOW_FORCED,
                    InputMethodManager.HIDE_IMPLICIT_ONLY);

        }
    }

    /**
     * 关闭软键盘
     *
     * @param mEditText 输入框
     */
    public static void closeKeybord(EditText mEditText) {
        InputMethodManager imm = (InputMethodManager) mEditText.getContext()
                .getSystemService(Context.INPUT_METHOD_SERVICE);

        imm.hideSoftInputFromWindow(mEditText.getWindowToken(), 0);
    }

    /**
     * 关闭软键盘
     */
    public static void closeKeybord(Activity activity) {
        InputMethodManager imm = (InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE);
        if (imm != null) {
            imm.hideSoftInputFromWindow(activity.getWindow().getDecorView().getWindowToken(),
                    0);
        }
    }


    /**
     * 判断软键盘是否弹出
     */
    public static boolean isKeyboardOpened(View v) {
        InputMethodManager imm = (InputMethodManager) v.getContext().getSystemService(v.getContext().INPUT_METHOD_SERVICE);
        if (imm.hideSoftInputFromWindow(v.getWindowToken(), 0)) {
            imm.showSoftInput(v, 0);
            return true;
            //软键盘已弹出
        } else {
            return false;
            //软键盘未弹出
        }
    }


    /**
     * 获得屏幕宽度
     *
     * @param context
     * @return
     */
    public static int getScreenWidth(Context context) {
        WindowManager wm = (WindowManager) context
                .getSystemService(Context.WINDOW_SERVICE);
        DisplayMetrics outMetrics = new DisplayMetrics();
        wm.getDefaultDisplay().getMetrics(outMetrics);
        return outMetrics.widthPixels;
    }

    /**
     * 获得屏幕高度
     *
     * @param context
     * @return
     */
    public static int getScreenHeight(Context context) {
        WindowManager wm = (WindowManager) context
                .getSystemService(Context.WINDOW_SERVICE);
        DisplayMetrics outMetrics = new DisplayMetrics();
        wm.getDefaultDisplay().getMetrics(outMetrics);
        return outMetrics.heightPixels;
    }

    /**
     * 创建一个(icon + text)类型的Tab按钮
     */
    public static QMUITabSegment.Tab createTab(Context context, @DrawableRes int normalIcon, @DrawableRes int selectIcon, String text) {
        return new QMUITabSegment.Tab(
                ContextCompat.getDrawable(context, normalIcon),
                ContextCompat.getDrawable(context, selectIcon),
                text, false
        );
    }

    /**
     * 创建一个(icon + text)类型的Tab按钮，并按指定尺寸显示icon
     */
    public static QMUITabSegment.Tab createTab(Context context, int iconWidtn, int iconHeight, @DrawableRes int normalIcon, @DrawableRes int selectIcon, String text) {
        Bitmap normalBitmap = BitmapFactory.decodeResource(context.getResources(),
                normalIcon);
        Bitmap selectBitmap = BitmapFactory.decodeResource(context.getResources(),
                selectIcon);

        Drawable normalDrawble = new BitmapDrawable(BitmapUtils.scaleBitmap(normalBitmap, iconWidtn, iconHeight));
        Drawable selectDrawble = new BitmapDrawable(BitmapUtils.scaleBitmap(selectBitmap, iconWidtn, iconHeight));

        return new QMUITabSegment.Tab(normalDrawble, selectDrawble, text, false);
    }


    /**
     * 创建一个(text)类型的Tab按钮
     */
    public static QMUITabSegment.Tab createTab(String text) {
        return new QMUITabSegment.Tab(text);
    }


    /**
     * 创建一个只包含 Text 的item按钮
     */
    public static QMUICommonListItemView createItemView(int id, QMUIGroupListView groupListView, @StringRes int titleId) {
        return createChevronItemView(id, groupListView, groupListView.getContext().getString(titleId));
    }

    public static QMUICommonListItemView createItemCiew(int id, QMUIGroupListView groupListView, String title) {
        QMUICommonListItemView itemWithChevron = groupListView.createItemView(title);
        itemWithChevron.setId(id);
        return itemWithChevron;
    }

    /**
     * 创建一个 Text + 右箭头的 item按钮
     */
    public static QMUICommonListItemView createChevronItemView(int id, QMUIGroupListView groupListView, @StringRes int titleId) {
        return createChevronItemView(id, groupListView, groupListView.getContext().getString(titleId));
    }

    public static QMUICommonListItemView createChevronItemView(int id, QMUIGroupListView groupListView, String title) {
        QMUICommonListItemView itemWithChevron = createItemCiew(id, groupListView, title);
        itemWithChevron.setAccessoryType(QMUICommonListItemView.ACCESSORY_TYPE_CHEVRON);
        return itemWithChevron;
    }


    /**
     * 模拟返回键
     */
    public static void doBack() {
        Observable.create(new ObservableOnSubscribe<Object>() {
            @Override
            public void subscribe(ObservableEmitter<Object> emitter) throws Exception {
                try {
                    Instrumentation inst = new Instrumentation();
                    inst.sendKeyDownUpSync(KeyEvent.KEYCODE_BACK);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        })
                .subscribeOn(Schedulers.io())
                .subscribe();
    }


}
