package com.efounder.chat.service;

import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import androidx.core.app.NotificationCompat;
import androidx.core.content.ContextCompat;

import com.efounder.chat.R;
import com.efounder.chat.utils.ImNotificationUtil;
import com.efounder.constant.EnvironmentVariable;
import com.efounder.util.AppContext;
import com.efounder.util.EnvSupportManager;
import com.efounder.util.MobilePushUtils;
import com.efounder.utils.ResStringUtil;
import com.utilcode.util.AppUtils;

import static com.efounder.chat.utils.ImNotificationUtil.CHANNEL_ID_BACKGROUND_SERVICE;
import static com.efounder.frame.utils.Constants.CHAT_PASSWORD;
import static com.efounder.frame.utils.Constants.CHAT_USER_ID;

/**
 * 创建前台服务代理
 *
 * @autor yqs
 * @date 2019/4/2 17:18
 **/
public class ForegroundServiceDelegate {
    private Service service;

    public ForegroundServiceDelegate(Service service) {
        this.service = service;
    }

    public void startForeground() {

        //如果系统版本大于8.0 并且不支持推送，需要通知栏显示
        if (shouldSupportForeground()) {
            startForegroundNotification(service);
            Intent intent = new Intent(service, BootstartService.class);
            service.startService(intent);
        }
    }

    public void stopForeground(boolean stop) {
        //如果系统版本大于8.0 并且不支持推送，需要通知栏显示
        if (shouldSupportForeground()) {
            service.stopForeground(stop);
        }
    }

    /**
     * 是否需要开启前台服务
     *
     * @return
     */
    public static boolean shouldSupportForeground() {
        ////如果系统版本大于8.0 ,并且支持消息服务，但是不支持推送，配置了需要通知栏显示的开关，那么返回允许开启前台服务
        int targetSdkVersion = AppContext.getInstance().getApplicationInfo().targetSdkVersion;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O
                && !MobilePushUtils.isSupportPush()
                && EnvSupportManager.isSupportIM()
                && targetSdkVersion >= Build.VERSION_CODES.O
                && EnvSupportManager.isSupportIMForegroundService()
                ) {
            return true;
        }
        return false;
    }

    /**
     * 启动 前台服务通知
     *
     * @param context
     */
    public static void startForegroundNotification(Service context) {
        ImNotificationUtil.createNotificationChannel(context);
        NotificationCompat.Builder builder = new NotificationCompat.Builder(context, CHANNEL_ID_BACKGROUND_SERVICE);
        builder.setContentTitle(AppUtils.getAppName() + ResStringUtil.getString(R.string.wechatview_need_keep_running));
        builder.setContentText(ResStringUtil.getString(R.string.wechatview_click_to_see_app));
        //todo 不设置setSmallIcon这个上面的文字就不会生效、、、o(︶︿︶)o 唉,坑死我了
        builder.setSmallIcon(R.drawable.icon_service_isruning);
        //设置点击打开应用首页
        PendingIntent pendingIntent = getPendingIntent(context);
        if (pendingIntent != null) {
            builder.setContentIntent(pendingIntent);
        }

        context.startForeground(8888, builder.build());
    }

    //获取打开应用主页tabottomactivity的PendingIntent
    private static PendingIntent getPendingIntent(Service context) {
        //检查是否登录
        String chatUserID = EnvironmentVariable.getProperty(CHAT_USER_ID);
        String chatPassword = EnvironmentVariable.getProperty(CHAT_PASSWORD);
        String pingtaiPassword = EnvironmentVariable.getPassword();
        String userName = EnvironmentVariable.getUserName();
        if (null == chatUserID || "".equals(chatUserID) || null == chatPassword
                || "".equals(chatPassword) || null == pingtaiPassword || "".equals(pingtaiPassword)) {
            //没有登录,不允许打开用于主页
            return null;
        }

        PendingIntent pendingIntent = null;
        try {
            Class clazz = null;
            clazz = Class.forName(context.getResources().getString(R.string.from_group_backto_first));
            Intent intent = null;
            intent = new Intent(context, clazz);
            //不检查应用更新
            intent.putExtra("unDoCheck", "");
            pendingIntent = PendingIntent.getActivity(context, 12,
                    intent, PendingIntent.FLAG_UPDATE_CURRENT);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return pendingIntent;
    }


    public static void startService(Context context, Intent intent) {
        if (shouldSupportForeground()) {
            ContextCompat.startForegroundService(context, intent);
        } else {
            context.startService(intent);

        }
    }

//    //首先使用PowerManager.isIgnoringBatteryOptimizations判断是否有已经加入了
//    private boolean isIgnoringBatteryOptimizations() {
//        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
//            String packageName = Utils.getApp().getPackageName();
//            PowerManager pm = (PowerManager) Utils.getApp().getSystemService(Context.POWER_SERVICE);
//            return pm.isIgnoringBatteryOptimizations(packageName);
//        }
//        return false;
//
//    }
//
//    //如果未加入，则需要通过Settings.ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS拉起请求弹窗
//    public static void gotoSettingIgnoringBatteryOptimizations() {
//        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
//            try {
//                Intent intent = new Intent();
//                String packageName = Utils.getApp().getPackageName();
//                intent.setAction(Settings.ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS);
//                intent.setData(Uri.parse("package:" + packageName));
//                ActivityUtils.getTopActivity().startActivityForResult(intent, 15);
//            } catch (Exception e) {
//                e.printStackTrace();
//            }
//        }
//
//    }
}
