package com.ux.video.file.filerecovery.base

import android.annotation.SuppressLint
import android.graphics.Color
import android.os.Bundle
import android.os.CountDownTimer
import android.view.Gravity
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.core.graphics.drawable.toDrawable
import androidx.fragment.app.DialogFragment
import com.ux.video.file.filerecovery.databinding.DialogRecoveringBinding


abstract class BaseIngDialogFragment(var total: Int, var complete: () -> Unit) : DialogFragment() {

    private lateinit var binding: DialogRecoveringBinding


    override fun onStart() {
        super.onStart()
        dialog?.window?.apply {
            setLayout(
                ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.WRAP_CONTENT
            )
            setGravity(Gravity.BOTTOM)
            setBackgroundDrawable(Color.TRANSPARENT.toDrawable())
        }
    }

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        binding = DialogRecoveringBinding.inflate(inflater)
        initUi(binding)
        binding.run {
            if (total < 20) {
                val defaultTimer = 2000L
                object : CountDownTimer(defaultTimer, 200) {
                    override fun onFinish() {
                        progressBar.progress = 100
                        complete.invoke()
                    }

                    override fun onTick(millisUntilFinished: Long) {
                        var progressPercentage = ((100 * millisUntilFinished) / defaultTimer)
                        val i = (100 - progressPercentage).toInt()
                        progressBar.progress = i
                    }

                }.start()
            }
        }


        return binding.root
    }

    protected abstract fun initUi(binding: DialogRecoveringBinding)

    @SuppressLint("SetTextI18n")
    fun updateProgress(number: Int) {
        binding.tvRecoverNumber.text = "${number}/"
        if (total < 20) {
            return
        }
        val progress = if (total > 20) {
            (number * 100f / total).toInt()
        } else {
            0
        }
        binding.progressBar.progress = progress

        if (progress == 100) {
            complete.invoke()
        }
    }


}
