package com.develop.common.utils

import android.content.Context
import android.os.Handler
import android.os.Looper
import android.os.Message
import com.develop.common.R
import java.text.SimpleDateFormat
import java.util.*

class TimerUtils(var context: Context) {
    private var timer: Timer? = null

    private var timerTask: TimerTask? = null
    private var isStartCount = false
    private var callback: OnTimeCountCallback? = null
    private val mCalHandler = object : Handler(Looper.getMainLooper()) {
        override fun handleMessage(msg: Message) {
            super.handleMessage(msg)
            callback?.onCount(getTime("HH:mm"), getTime("yyyy-MM-dd"), getWeek(), isNight())
        }

    }


    fun startTicker(callback: OnTimeCountCallback) {
        this.callback = callback
        isStartCount = true
        if (timerTask == null) {
            timerTask = object : TimerTask() {
                override fun run() {
                    val message = mCalHandler.obtainMessage()
                    mCalHandler.sendMessage(message)
                }


            }
        }
        if (timer == null) {
            timer = Timer()
        }
        timer?.schedule(timerTask, 0, 10)
    }

    fun stopTicker() {
        timer?.cancel()
        timer = null
        timerTask?.cancel()
        timerTask = null
        callback = null
    }

    interface OnTimeCountCallback {
        fun onCount(timeStr: String, dateStr: String, weakStr: String, isNight: Boolean)
    }


    private fun getWeek(): String {
        val calender = Calendar.getInstance()
        var mWay = calender.get(Calendar.DAY_OF_WEEK).toString()
        when (mWay) {
            "1" -> {
                mWay = context.getString(R.string.sunday)
            }
            "2" -> {
                mWay = context.getString(R.string.monday)
            }
            "3" -> {
                mWay = context.getString(R.string.tuesday)
            }
            "4" -> {
                mWay = context.getString(R.string.wednesday)
            }
            "5" -> {
                mWay = context.getString(R.string.thursday)
            }
            "6" -> {
                mWay = context.getString(R.string.friday)
            }
            "7" -> {
                mWay = context.getString(R.string.saturday)
            }
        }
        return mWay
    }

    private fun getTime(format: String): String {
        val simpleDateFormat = SimpleDateFormat(format, Locale.CHINA)
        //获取当前时间
        val date = Date(System.currentTimeMillis())
        return simpleDateFormat.format(date)
    }

    private fun isNight(): Boolean {
        val time = getTime("HH").toInt()
        if (time in 6..18) {
            return false
        }
        return true
    }

}