package com.duben.microtribe.ui.widgets

import android.app.Dialog
import android.content.Context
import android.view.Gravity
import android.view.KeyEvent
import android.view.View
import android.view.WindowManager
import android.widget.ImageView
import android.widget.TextView
import com.downloader.PRDownloader
import com.downloader.Progress
import com.duben.microtribe.R
import com.duben.microtribe.utils.CacheUtil
import com.duben.library.utils.nodoubleclick.AntiShake
import java.util.*

/**
 * 下载进度弹窗
 */
class DownloadProgressDialog(context: Context) :
        Dialog(context, R.style.dialog), View.OnClickListener {

    private var tvDownloadProgress: TextView? = null

    init {
        setContentView(R.layout.dialog_download_progress)
        // 设置window属性
        val lp = window!!.attributes
        lp.gravity = Gravity.CENTER
        lp.width = WindowManager.LayoutParams.MATCH_PARENT
        lp.windowAnimations = R.style.DialogAnimBottom
        window!!.attributes = lp

        // 设置外部不可关闭
        setCancelable(false)
        setCanceledOnTouchOutside(false)
        setOnKeyListener { _, i, _ ->
            i == KeyEvent.KEYCODE_BACK
        }

        findViewById<ImageView>(R.id.iv_download_quit).setOnClickListener(this)
        tvDownloadProgress = findViewById(R.id.tv_download_progress)
    }

    override fun onClick(v: View) {
        if (AntiShake.check(v?.id)) return
        when (v.id) {
            R.id.iv_download_quit -> {
                PRDownloader.cancelAll()
                CacheUtil.clearAllCache()

                dismiss()
            }
        }
    }

    fun setProgress(progress: Progress) {
        tvDownloadProgress?.text = "正在下载  " + getProgressDisplayLine(progress.currentBytes, progress.totalBytes)
    }

    fun getProgressDisplayLine(currentBytes: Long, totalBytes: Long): String? {
        return getBytesToMBString(currentBytes) + "/" + getBytesToMBString(totalBytes)
    }

    private fun getBytesToMBString(bytes: Long): String {
        return String.format(Locale.ENGLISH, "%.2fMB", bytes / (1024.00 * 1024.00))
    }
}