package com.frame.base.server;

import android.app.Notification;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.IBinder;
import android.os.PowerManager;
import android.support.annotation.Nullable;

import com.base.utils.Config;
import com.base.utils.base.BaseApp;
import com.base.utils.tools.android.ActivityUtil;
import com.frame.base.FrameApp;
import com.frame.base.bean.BeanHeartbeat;
import com.frame.base.manager.MyFrameManager;

/**
 * 常驻的服务
 * 1.设置屏幕是否常亮
 * ====================
 * 2.心跳
 */

public class MyFrameService extends Service {

    private Context mContext;
    private static PowerManager powerManager = null;
    private static PowerManager.WakeLock wakeLock = null;     //保持屏幕常亮

    @Override
    public void onCreate() {
        super.onCreate();
        mContext = this;
        powerManager = (PowerManager) getSystemService(POWER_SERVICE);
        wakeLock = powerManager.newWakeLock(PowerManager.FULL_WAKE_LOCK, "AppServiceLock");
        //这个函数的作用是是不是需要计算锁的数量，设置为false时，在release（）的时候，不管你acquire()了多少回，可以releaseWakeLock掉
        //没有设置
        wakeLock.setReferenceCounted(false);
        //这个，报错为：java.lang.RuntimeException: WakeLock under-locked

        //Toast.makeText(FrameApp.getInstance(), "是否唤醒屏幕保持常亮："+MyFrameManager.getInstance().isKeepWake(), Toast.LENGTH_SHORT).show();
        if (MyFrameManager.getInstance().isKeepWake()) {
            keepWake();
            //getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        }
        init();
        startForeground(1, new Notification());
    }


    private HeartThread heartThread;

    private void init() {
        heartThread = new HeartThread();
        heartThread.start();
    }

    /**
     * 保持屏幕唤醒
     */
    public static void keepWake() {
        if (wakeLock != null) {
            wakeLock.acquire();
        }
    }

    /**
     * 释放 屏幕常亮
     */
    public static void wakeRelease() {
        if (wakeLock != null) {
            wakeLock.release();
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (MyFrameManager.getInstance().isKeepWake()) {
            wakeRelease();
        }
        destroy();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public boolean onUnbind(Intent intent) {
        return super.onUnbind(intent);
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }


    private void destroy() {
        if (heartThread != null) {
            Config.isOpenHeartbeat = false;
            heartThread.interrupt();
            heartThread = null;
        }
    }

    private long heartCount = 0;            //跳了多少次
    private BeanHeartbeat beanHeartbeat;            //心跳实体

    public BeanHeartbeat getBeanHeartbeat() {
        return beanHeartbeat;
    }

    /**
     * 心跳线程
     */
    class HeartThread extends Thread {
        @Override
        public void run() {
            super.run();
            while (Config.isOpenHeartbeat) {
                try {
                    Thread.sleep(Config.heartbeatInterval);
                    heartCount += 1;

                    beanHeartbeat = new BeanHeartbeat();
                    beanHeartbeat.setAccount(BaseApp.getDeviceInfo().getAndroidId());
                    beanHeartbeat.setBackground(ActivityUtil.appIsBackground(mContext));
                    beanHeartbeat.setCount(heartCount);
                    beanHeartbeat.setTime(System.currentTimeMillis());

                    if (FrameApp.getInstance().getOnFrameAppListener() != null) {
                        FrameApp.getInstance().getOnFrameAppListener().onHeartbeat(beanHeartbeat);
                    }

                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }

}
