package com.base.browserwhite.ui.activity.splash

import android.os.Handler
import com.base.browserwhite.databinding.ActivitySplash2Binding

class TaskManager {


    private val binding: ActivitySplash2Binding

    private var mHandler: Handler

    private var mIsPaused = false
    private var mProgress = 0

    private val listener: ProgressListener

    constructor(binding: ActivitySplash2Binding, listener: ProgressListener) {
        this.binding = binding
        this.listener = listener
        mHandler = Handler()
        initView()
    }

    var loadTime: Int = 15

    private fun initView() {
        //loadTime = SPUtils.getInstance().getInt("loading_page_time", 15)
        binding.pb.max = loadTime
        binding.pb.progress = 0

    }

    fun startProgress() {

        val mRunnable: Runnable = object : Runnable {
            override fun run() {
                if (!mIsPaused) {
                    mProgress++ // 计算进度
                    binding.pb.progress = mProgress
                    if (mProgress < loadTime) {
                        mHandler.postDelayed(this, 1000) // 每秒钟更新一次进度
                    } else {
                        listener.onProgressMax()
                        pauseProgress()
                    }
                }
            }
        }
        mHandler.postDelayed(mRunnable, 1000)
    }

    fun pauseProgress() {
        if (!mIsPaused) {
            mIsPaused = true
            mHandler.removeCallbacksAndMessages(null)
        }
    }

    fun maxProgress() {
        binding.pb.progress = binding.pb.max
        listener.onProgressMax()
    }

    interface ProgressListener {
        fun onProgressMax()
    }
}