package com.doverfuelingsolutions.issp.view

import android.app.DownloadManager
import android.content.Context
import android.content.Intent
import android.net.Uri
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 androidx.lifecycle.lifecycleScope
import com.doverfuelingsolutions.issp.R
import com.doverfuelingsolutions.issp.api.WayneApiConfig
import com.doverfuelingsolutions.issp.databinding.ActivityUpdateBinding
import com.doverfuelingsolutions.issp.utils.DFSToastUtil
import com.doverfuelingsolutions.issp.utils.NetworkUtil
import com.doverfuelingsolutions.issp.utils.StringUtil
import com.doverfuelingsolutions.issp.utils.WindowUtil
import com.doverfuelingsolutions.issp.utils.download.DownloadAction
import kotlinx.coroutines.launch
import java.io.File

class UpdateActivity : AppCompatActivity(),
    View.OnClickListener{

    companion object {

        fun start(context: Context, version: String, remoteFileName: String, description: String) {
            Intent(context, UpdateActivity::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()

    private var remoteFileName = ""
    private var localFileName = ""
    private var downloadAction: DownloadAction? = null

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

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

        viewModel.version.value = intent.getStringExtra("version") ?: ""
        viewModel.versionDescription.value = intent.getStringExtra("description") ?: ""
        intent.getStringExtra("remoteFileName").let {
            if (it.isNullOrBlank()) {
                DFSToastUtil.fail(R.string.invalid_version_file)
                finish()
                return
            }

            remoteFileName = it
            download()
        }

        viewModel.progress.observe(this, {
            binding.progressView.progress = it
        })
    }

    override fun onResume() {
        super.onResume()

        WindowUtil.setFullscreen(this)
    }

    override fun onClick(v: View?) {
        when (v) {
            binding.buttonRetry -> {
                downloadAction?.stop()
                download()
            }
            binding.reInstall -> {
                installApk()
            }
            binding.buttonCancel -> {
                downloadAction?.stop()
                finish()
            }
        }
    }

    private fun download() {
        viewModel.isCancel.value = false
        viewModel.isRetry.value = false
        viewModel.isRetry.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.isRetry.value = true
                        viewModel.errorText.value = StringUtil.get(R.string.download_fail)
                        downloadAction?.stop()
                    }
                    DownloadManager.STATUS_PAUSED -> {
                        viewModel.isCancel.value = true
                        if (NetworkUtil.isAvailable(this@UpdateActivity)) {
                            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.provider", 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 versionDescription = MutableLiveData("")
        val progress = MutableLiveData(0f)
        val isDownloaded = MutableLiveData(false)
        val isCancel = MutableLiveData(false)
        val isRetry = MutableLiveData(false)
        val errorText = MutableLiveData("")
    }
}