package com.xxfc.rv.other;

import android.app.Activity;
import android.app.Application;
import android.content.Context;
import android.os.Bundle;
import android.text.TextUtils;

import com.ruiwenliu.wrapper.util.AppUtils;
import com.rv.im.CustomerListActivity;
import com.rv.im.db.service.ChatMessageServiceImp;
import com.yuyife.okgo.OkGoUtil;

import me.leolin.shortcutbadger.ShortcutBadger;

public class RvActivityLifecycleCallbacks implements Application.ActivityLifecycleCallbacks {

    private static int ativiteCount;

    private static boolean isInChatView; // app是否正在聊天模块

    private static boolean isSpecialCases;  // 是否处于特殊情况，例如相机，图片选择

    @Override
    public void onActivityCreated(Activity activity, Bundle savedInstanceState) {
        if (CustomerListActivity.class.getSimpleName().equals(activity.getClass().getSimpleName())) {
            isInChatView = true;
        }
    }

    @Override
    public void onActivityStarted(Activity activity) {
        ativiteCount += 1;
    }

    @Override
    public void onActivityResumed(Activity activity) {

    }

    @Override
    public void onActivityPaused(Activity activity) {

    }

    @Override
    public void onActivityStopped(Activity activity) {
        ativiteCount -= 1;
        if (ativiteCount == 0) {
//            Toast.makeText(activity.getApplication(), "程序退到后台", Toast.LENGTH_SHORT).show();
            setBadger(activity.getApplicationContext());
        }
    }

    @Override
    public void onActivitySaveInstanceState(Activity activity, Bundle outState) {

    }

    @Override
    public void onActivityDestroyed(Activity activity) {
        if (CustomerListActivity.class.getSimpleName().equals(activity.getClass().getSimpleName())) {
            isInChatView = false;
        }
    }

    public static boolean isAppBackground() {
        return ativiteCount == 0 ? true : false && !isSpecialCases;
    }

    public static boolean isAppInChatView() {
        return isInChatView;
    }

    public static boolean isIsSpecialCases() {
        return isSpecialCases;
    }

    public static void setIsSpecialCases(boolean isSpecialCases) {
        RvActivityLifecycleCallbacks.isSpecialCases = isSpecialCases;
    }

    /********
     * 设置桌面未读消息数
     */
    public static void setBadger(Context context) {
        if (ShortcutBadger.isBadgeCounterSupported(context)) {
            if (TextUtils.isEmpty(OkGoUtil.getToken()))
                AppUtils.setBadger(context, 0);
            else
                AppUtils.setBadger(context, ChatMessageServiceImp.getInstance(context).getUnReadMsg());
        }
    }
}
