package com.doverfuelingsolutions.issp.view

import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.os.Environment
import android.view.View
import androidx.activity.viewModels
import androidx.appcompat.app.AppCompatActivity
import androidx.core.content.FileProvider
import androidx.databinding.DataBindingUtil
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import com.doverfuelingsolutions.issp.R
import com.doverfuelingsolutions.issp.databinding.ActivityUpdateBinding
import com.doverfuelingsolutions.issp.utils.*
import com.doverfuelingsolutions.issp.utils.download.DownloadAction
import com.tencent.bugly.beta.Beta
import com.tencent.bugly.beta.UpgradeInfo
import com.tencent.bugly.beta.download.DownloadListener
import com.tencent.bugly.beta.download.DownloadTask
import java.io.File

class UpgradeActivity : AppCompatActivity(),
    View.OnClickListener,
    DownloadListener {

    companion object {

        fun start(context: Context, version: String, remoteFileName: String, description: String) {
            Intent(context, UpgradeActivity::class.java).let {
                it.putExtra("version", version)
                it.putExtra("remoteFileName", remoteFileName)
                it.putExtra("description", description)

                context.startActivity(it)
            }
        }
    }

    private val binding: ActivityUpdateBinding by lazy {
        DataBindingUtil.setContentView(this, R.layout.activity_update)
    }
    private val viewModel: UpdateViewModel by viewModels()

    /* DIY */
    private var remoteFileName = ""
    private var localFileName = ""
    private var downloadAction: DownloadAction? = null

    private var upgradeInfo: UpgradeInfo? = null
    private var downloadTask: DownloadTask? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        supportActionBar?.hide()

        binding.lifecycleOwner = this
        binding.viewModel = viewModel
        binding.handler = this

        /* bugly */
        Beta.registerDownloadListener(this)
        upgradeInfo = Beta.getUpgradeInfo()
        viewModel.version.value = upgradeInfo!!.versionName
        viewModel.versionFeature.value = upgradeInfo!!.newFeature
        viewModel.versionPublishTime.value = TimeUtil.dateFormat(upgradeInfo!!.publishTime)

        // view control
        viewModel.progress.observe(this, {
            binding.progressView.progress = it
        })
        viewModel.taskStatus.observe(this, {
            viewModel.buttonVisible.value = true
            when (it) {
                DownloadTask.INIT -> {
                    viewModel.buttonText.value = StringUtil.get(R.string.start_upgrade)
                }
                DownloadTask.PAUSED -> {
                    viewModel.buttonText.value = StringUtil.get(R.string.continue_upgrade)
                }
                DownloadTask.DELETED,
                DownloadTask.FAILED -> {
                    viewModel.buttonText.value = StringUtil.get(R.string.retry)
                }
                DownloadTask.COMPLETE -> {
                    viewModel.buttonText.value = StringUtil.get(R.string.install_app)
                }
                DownloadTask.DOWNLOADING -> {
                    viewModel.buttonVisible.value = false
                }
            }
        })
    }

    override fun onResume() {
        super.onResume()

        WindowUtil.setFullscreen(this)
    }

    override fun onDestroy() {
        super.onDestroy()

        Beta.unregisterDownloadListener()
    }

    override fun onClick(v: View?) {
        when (v) {
            binding.buttonAction -> {
                when (viewModel.taskStatus.value) {
                    DownloadTask.INIT -> {
                        downloadTask = Beta.startDownload()
                        viewModel.taskStatus.value = downloadTask!!.status
                    }
                    DownloadTask.DELETED,
                    DownloadTask.PAUSED,
                    DownloadTask.FAILED -> {
                        if (!NetworkUtil.isAvailable(this)) {
                            DFSToastUtil.fail(R.string.network_none)
                        } else if (downloadTask?.status != DownloadTask.COMPLETE && DownloadTask.DOWNLOADING != downloadTask?.status) {
                            downloadTask?.download()
                        }
                    }
                    DownloadTask.COMPLETE -> {
                        Beta.installApk(downloadTask?.saveFile)
                    }
                }
            }
            binding.buttonCancel -> {
                downloadTask?.stop()
                Beta.cancelDownload()
                finish()
            }
        }
    }

    /* bugly */
    override fun onReceive(task: DownloadTask) {
        if (task.status != viewModel.taskStatus.value) {
            viewModel.taskStatus.value = task.status
        }

        viewModel.progress.value = if (task.savedLength > 0 && task.totalLength > 0) {
            task.savedLength.toFloat() * 100 / task.totalLength.toFloat()
        } else {
            0f
        }
    }

    override fun onCompleted(task: DownloadTask) {
        viewModel.taskStatus.value = task.status
    }

    override fun onFailed(task: DownloadTask, code: Int, msg: String) {
        viewModel.taskStatus.value = task.status
        viewModel.errorText.value = if (!NetworkUtil.isAvailable(this)) {
            StringUtil.get(R.string.cant_download_no_net)
        } else {
            msg
        }
    }

    /* DIY */
    private fun check() {
        viewModel.version.value = intent.getStringExtra("version") ?: ""
        viewModel.versionFeature.value = intent.getStringExtra("description") ?: ""
        intent.getStringExtra("remoteFileName").let {
            if (it.isNullOrBlank()) {
                DFSToastUtil.fail(R.string.invalid_version_file)
                finish()
                return
            }

            remoteFileName = it
            download()
        }
    }

    private fun download() {
//        viewModel.isCancel.value = false
//        viewModel.isContinue.value = false
//        viewModel.isContinue.value = false
//
//        localFileName = "update/$remoteFileName"
//        downloadAction = DownloadAction(
//            this,
//            Uri.parse("${WayneApiConfig.HOST_ASSETS}/isspt/$remoteFileName"),
//            localFileName)
//        downloadAction?.start { status, size, total ->
//            lifecycleScope.launch {
//                when (status) {
//                    DownloadManager.STATUS_RUNNING -> {
//                        viewModel.errorText.value = ""
//                        viewModel.progress.value = size.toFloat() * 100 / total
//                    }
//                    DownloadManager.STATUS_SUCCESSFUL -> {
//                        viewModel.errorText.value = ""
//                        viewModel.progress.value = 100f
//                        viewModel.isCancel.value = true
//                        viewModel.isDownloaded.value = true
//
//                        installApk()
//                    }
//                    DownloadManager.STATUS_FAILED -> {
//                        viewModel.isCancel.value = true
//                        viewModel.isContinue.value = true
//                        viewModel.errorText.value = StringUtil.get(R.string.download_fail)
//                        downloadAction?.stop()
//                    }
//                    DownloadManager.STATUS_PAUSED -> {
//                        viewModel.isCancel.value = true
//                        if (NetworkUtil.isAvailable(this@UpgradeActivity)) {
//                            viewModel.errorText.value = StringUtil.get(R.string.download_pause_no_network)
//                        } else {
//                            viewModel.errorText.value = StringUtil.get(R.string.download_pause)
//                        }
//                    }
//                }
//            }
//        }
    }

    private fun installApk() {
        getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS)?.let { folder ->
            val file = File("${folder.absolutePath}/$localFileName")
            if (!file.isFile) {
                DFSToastUtil.fail(R.string.cant_find_local_file)
                finish()
                return@let
            }

            // 先删掉其他APK
            file.parentFile?.list()?.forEach {
                File(it).let { f ->
                    if (f.absolutePath != file.absolutePath && f.isFile && f.name.endsWith("apk")) {
                        f.delete()
                    }
                }
            }

            // 安装
            val fileUri = FileProvider.getUriForFile(this, "$packageName.fileProvider", file)
            Intent(Intent.ACTION_VIEW).let { intent ->
                intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
                intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
                intent.setDataAndType(fileUri, "application/vnd.android.package-archive")
                this.startActivity(intent)
            }
        }
    }

    class UpdateViewModel : ViewModel() {
        val version = MutableLiveData("1.0.0")
        val versionFeature = MutableLiveData("")
        val versionPublishTime = MutableLiveData("")
        val progress = MutableLiveData(0f)

        val taskStatus = MutableLiveData(DownloadTask.INIT)
        val buttonText = MutableLiveData(StringUtil.get(R.string.start_upgrade))
        val buttonVisible = MutableLiveData(true)

        val errorText = MutableLiveData("")
    }
}