package com.hainaos.vc.utils;

import android.annotation.SuppressLint;
import android.content.Context;
import android.os.Build;
import android.os.Handler;
import android.os.Looper;
import android.widget.Toast;

import com.hainaos.vc.BuildConfig;


/**
 * Created by haoge on 2017/3/2.
 */

public class ToastUtil {
    private static Handler mainHandler = new Handler(Looper.getMainLooper());
    private static Toast toast;
    private static Context mContext;

    @SuppressLint("ShowToast")
    public static void init(Context context) {
        mContext = context;
        toast = Toast.makeText(mContext, "", Toast.LENGTH_SHORT);
        debugToast = Toast.makeText(mContext, "", Toast.LENGTH_SHORT);

    }

    private static long time1 = 0L;
    private static long time2 = 0L;

    public static void show(final String msg) {
        mainHandler.post(new Runnable() {
            @Override
            public void run() {
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                    time2 = System.currentTimeMillis();
                    if ((time2 - time1) > 3499) {
                        showToast(mContext, msg, Toast.LENGTH_LONG);
//                        Log.e("fht", "LENGTH_LONG");
                        time1 = time2;
                    }
                } else {
                    if (toast != null) {
                        toast.setText(msg);
                        toast.show();
                    }
                }
            }
        });

    }

    private static Toast mToast = null;


    public static void showToast(Context context, String text, int duration) {
        if (Build.VERSION.SDK_INT == Build.VERSION_CODES.P) {
            Toast.makeText(context, text, duration).show();
        } else {
            if (mToast == null) {
                mToast = Toast.makeText(context, text, duration);
            } else {
                mToast.setText(text);
                mToast.setDuration(duration);
            }
            mToast.show();
        }
    }


    static Handler debugHandler = new Handler(Looper.getMainLooper());
    static Toast debugToast;

    public static void debugShow(final String msg) {
        mainHandler.post(new Runnable() {
            @Override
            public void run() {
                if (BuildConfig.DEBUG) {
                    if (toast != null) {
                        toast.setText(msg);
                        toast.show();
                    }
                }
            }
        });
    }

}
