package com.test.basd.smartjunkcleaner.activity.splash

import android.os.Handler
import com.blankj.utilcode.util.SPUtils
import com.test.basd.smartjunkcleaner.databinding.ActivityLayoutSplashBinding

class ProgressManager {


    private val binding: ActivityLayoutSplashBinding

    private var mHandler: Handler

    private var mIsPaused = false
    private var mProgress = 0

    private val listener:ProgressListener

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


    private fun initView() {
        val 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 < 9) {
                        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()
    }

    fun resumeProgress() {
        if (mIsPaused) {
            mIsPaused = false
            startProgress()
        }
    }

    interface ProgressListener{
         fun onProgressMax()
    }
}