package com.bxzk.afxj.util;

import android.content.Context;
import android.graphics.Color;
import android.view.Gravity;
import android.widget.TextView;
import android.widget.Toast;

import com.bxzk.afxj.R;
import com.bxzk.afxj.application.BApplication;


/**
 * Created by shi on 2017/3/9.
 */

/**
 * Toast工具类
 * 实现全局toast不会重复显示 节省资源
 */

public class ToastUtils {

    /**
     * 之前显示的内容
     */
    private static String oldMsg;
    /**
     * Toast对象
     */
    private static Toast toast = null;
    /**
     * 第一次时间
     */
    private static long oneTime = 0;
    /**
     * 第二次时间
     */
    private static long twoTime = 0;

    public static void showToast(Context context, int resource) {
        showToast(context, context.getResources().getString(resource));
    }

    public static void showToast(int resource) {
        showToast(BApplication.getContext(), BApplication.getContext().getResources().getString(resource));
    }

    public static void showToast(String msg) {

        showToast(BApplication.getContext(), msg);
    }


    public static void showToast(final Context context, final String message) {


        try {
            TextView view = new TextView(context);
            view.setBackgroundResource(R.drawable.shanpe_toast);
            view.setTextColor(Color.WHITE);
            view.setTextSize(14f);
            view.setPadding(DensityUtils.dip2px(54), DensityUtils.dip2px( 7), DensityUtils.dip2px( 54), DensityUtils.dip2px( 7));
            view.setText(message);

            if (toast == null) {
                toast = Toast.makeText(context, message, Toast.LENGTH_SHORT);
                toast.setGravity(Gravity.CENTER,0,0);
                toast.setView(view);

                toast.show();
                oneTime = System.currentTimeMillis();
                oldMsg = message;
            } else {
                twoTime = System.currentTimeMillis();
               TextView mtv = (TextView) toast.getView();
                mtv.setText(message);
                if (message.equals(oldMsg)) {
                    if (twoTime - oneTime > Toast.LENGTH_SHORT) {

                        toast.show();
                    }
                } else {
                    oldMsg = message;
                    if (twoTime - oneTime > Toast.LENGTH_SHORT) {
                        toast.show();
                    }
                }
            }
            oneTime = twoTime;
        } catch (Exception e) {
            Log.e("www:" + e.getMessage());
        }
    }


}