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.Color;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.support.annotation.ColorRes;
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.text.SpannableString;
import android.text.SpannableStringBuilder;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.style.ForegroundColorSpan;
import android.util.DisplayMetrics;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.qmuiteam.qmui.util.QMUIStatusBarHelper;
import com.qmuiteam.qmui.widget.QMUITopBar;

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


/**
 * Created by SiKang on 2018/9/14.
 * 常用UI功能
 */
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(RecyclerView recyclerView, RecyclerView.Adapter adapter) {
        recyclerView.setLayoutManager(new LinearLayoutManager(recyclerView.getContext()));
        recyclerView.setAdapter(adapter);
        recyclerView.setItemAnimator(new DefaultItemAnimator());
    }


    public static boolean hasEmptyValue(View... views) {
        for (View view : views) {
            if (view == null) {
                return true;
            }
            if (view instanceof TextView) {
                if (TextUtils.isEmpty(((TextView) view).getText().toString().replace(" ", ""))) {
                    return true;
                }
            } else if (view instanceof EditText) {
                if (TextUtils.isEmpty(((EditText) view).getText().toString().replace(" ", ""))) {
                    return true;
                }
            }
        }
        return false;
    }


    /**
     * 显示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();
    }


    /**
     * 显示View
     */
    public static void showViews(View view, View... views) {
        view.setVisibility(View.VISIBLE);
        for (View v : views) {
            v.setVisibility(View.VISIBLE);
        }
    }

    /**
     * 显示View
     */
    public static void showFirst(View view, View... views) {
        view.setVisibility(View.VISIBLE);
        for (View v : views) {
            v.setVisibility(View.GONE);
        }
    }

    /**
     * 隐藏View
     */
    public static void hideViews(View view, View... views) {
        view.setVisibility(View.GONE);
        for (View v : views) {
            v.setVisibility(View.GONE);
        }
    }


    /**
     * 设置View Selected 状态
     */
    public static void unSelectedViews(View view, View... views) {
        view.setSelected(false);
        for (View v : views) {
            v.setSelected(false);
        }
    }

    public static void selectedViews(View view, View... views) {
        view.setSelected(false);
        for (View v : views) {
            v.setSelected(false);
        }
    }


    /**
     * 字符串高亮显示部分文字
     *
     * @param textView  控件
     * @param text      要高亮显示的文字（输入的关键词）
     * @param highTexts 高亮文字
     */
    public static void setTextHighLight(TextView textView, String text, int colorId, String... highTexts) {
        SpannableStringBuilder builder = new SpannableStringBuilder(text);
        // 遍历要显示的文字
        for (String highText : highTexts) {
            if (!TextUtils.isEmpty(highText) && text.contains(highText)) {
                int index = text.indexOf(highText);
                builder.setSpan(new ForegroundColorSpan(textView.getContext().getResources().getColor(colorId)), index, index + highText.length(), Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
            }
        }
        // 设置控件
        textView.setText(builder);
    }


    /**
     * public void
     *
     * */

    /**
     * 打开软键盘
     *
     * @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;
    }


    /**
     * 模拟返回键
     */
    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();
    }


}
