package com.example.sleep.service;

import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.Service;
import android.content.Intent;
import android.os.Build;
import android.os.IBinder;
import android.support.v4.app.NotificationCompat;

import com.example.sleep.R;
import com.example.sleep.database.GetRecord;

import java.util.Calendar;
import java.util.Timer;
import java.util.TimerTask;

import static com.example.sleep.database.GetRecord.getRecord;

public class GoSleepService extends Service {
    NotificationManager mManager;
    Notification.Builder sleep;

    GetRecord myGet;

    int hour;
    int min;
    boolean ifSleep = false;
    boolean notification_on = false;

    Timer timer;

    /**
     * 初始化，顺便获取当天是否已经睡觉记录，如已睡觉则不再提醒。
     */
    @Override
    public void onCreate() {
        super.onCreate();
        // 获取睡眠记录
        myGet = getRecord();
        // 获取通知管理器
        mManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        // 创建睡眠通知
        sleep = createNotification();
        // 休眠3秒，避免立即执行任务
        try {
            Thread.sleep(3000);
        } catch (InterruptedException ignored) {
        }
        // 获取提醒时间
        String remind = myGet.getRemind();
        String[] res = remind.split(":");
        hour = Integer.parseInt(res[0]);
        min = Integer.parseInt(res[1]);
        // 检查当天是否已经睡觉
        ifSleep = ifSleepToday();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        // 创建定时任务
        TimerTask timerTask = new TimerTask() {
            @Override
            public void run() {
                // 如果未睡觉且通知未显示，则检查是否到达提醒时间
                if (!ifSleep && !notification_on) {
                    Calendar now = Calendar.getInstance();
                    if ((now.get(Calendar.HOUR_OF_DAY)) >= hour && (now.get(Calendar.MINUTE)) >= min) {
                        // 显示睡眠提醒通知
                        mManager.notify(2, sleep.build());
                        notification_on = true;
                    }
                }
            }
        };
        // 创建并执行定时任务，每30秒检查一次
        timer = new Timer();
        timer.schedule(timerTask, 0, 30000);
        return START_STICKY;
    }

    // 此为开机自启成功与否测试
    Notification.Builder createMyNotification() {
        Notification.Builder builder = new Notification.Builder(this);
        builder
                .setContentTitle("睡眠助手")
                .setDefaults(NotificationCompat.DEFAULT_ALL);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            // 创建通知频道
            NotificationChannel channel = new NotificationChannel("3", "睡眠记录", NotificationManager.IMPORTANCE_DEFAULT);
            channel.canBypassDnd();
            channel.getAudioAttributes();
            channel.setBypassDnd(true);
            channel.setLockscreenVisibility(NotificationCompat.VISIBILITY_PUBLIC);
            mManager.createNotificationChannel(channel);
            builder.setChannelId("3");
        }
        return builder;
    }

    /**
     * 创建通知及通知频道
     *
     * @return 通知构造器
     */
    Notification.Builder createNotification() {
        Notification.Builder builder = new Notification.Builder(this);
        builder.setSmallIcon(R.drawable.sleep_1)
                .setContentTitle("睡眠助手")
                .setContentText("小助手提醒您该睡觉啦")
                .setOngoing(true)
                .setDefaults(NotificationCompat.DEFAULT_ALL).setOngoing(true);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            // 创建通知频道
            NotificationChannel channel = new NotificationChannel("2", "睡眠提醒", NotificationManager.IMPORTANCE_DEFAULT);
            channel.canBypassDnd();
            channel.getAudioAttributes();
            channel.setBypassDnd(true);
            channel.setLockscreenVisibility(NotificationCompat.VISIBILITY_PUBLIC);
            mManager.createNotificationChannel(channel);
            builder.setChannelId("2");
        }
        return builder;
    }

    /**
     * 今日是否睡觉
     *
     * @return 已睡觉，未睡觉
     **/
    public boolean ifSleepToday() {
        Calendar calendar = Calendar.getInstance();
        return !getRecord().queryByDate(((calendar.get(Calendar.MONTH) + 1) + "-" + calendar.get(Calendar.DAY_OF_MONTH))).isEmpty();
    }

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

    @Override
    public void onDestroy() {
        // 取消定时任务和通知
        timer.cancel();
        mManager.cancel(2);
        super.onDestroy();
    }
}

