package com.gamedog.vididin.features.benefit.widget

import android.content.Context
import android.os.CountDownTimer
import android.util.AttributeSet
import android.view.LayoutInflater
import android.widget.LinearLayout
import com.ama.core.architecture.util.DateUtil
import com.gamedog.vididin.manager.TaskManager
import com.viddin.videos.free.databinding.BenefitCountdownTimerViewBinding


class CounterDownTimerView @JvmOverloads constructor(
    context: Context,
    attrs: AttributeSet? = null,
    defStyleAttr: Int = 0
) : LinearLayout(context, attrs, defStyleAttr) {
    private lateinit var mTimer: CountDownTimer
    private var mBinding: BenefitCountdownTimerViewBinding


    init {
        mBinding = BenefitCountdownTimerViewBinding.inflate(LayoutInflater.from(context), this, true)
    }

    override fun onAttachedToWindow() {
        super.onAttachedToWindow()
        startTimer()
    }

    private fun startTimer() {
        val startMs = TaskManager.instance().boxTaskStatus().getCurrentBoxStartTimeMs()
        val totalMs = TaskManager.instance().boxTaskStatus().getCurrentBoxTotalDurationMs()

        val restMs = startMs + totalMs - System.currentTimeMillis()

        mTimer = object : CountDownTimer(restMs, 1000) {
            override fun onTick(millisUntilFinished: Long) {
                val resultList = DateUtil.formatMs2HMS(millisUntilFinished)
                mBinding.tvHour.text = resultList[0].toString()
                mBinding.tvMin.text = resultList[1].toString()
                mBinding.tvSecond.text = resultList[2].toString()
            }

            override fun onFinish() {
            }
        }.start()
    }

    fun restartTimer() {
        if (mTimer != null) {
            mTimer.cancel()
        }
        startTimer()
    }

    override fun onDetachedFromWindow() {
        super.onDetachedFromWindow()
        if (mTimer != null) {
            mTimer.cancel()
        }

    }

}