package com.doverfuelingsolutions.issp.view

import android.app.Activity
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.view.View
import androidx.appcompat.app.AppCompatActivity
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.FuelInfoApi
import com.doverfuelingsolutions.issp.api.SystemApi
import com.doverfuelingsolutions.issp.databinding.ActivityPreferenceBinding
import com.doverfuelingsolutions.issp.utils.AppUtil
import com.doverfuelingsolutions.issp.utils.DFSToastUtil
import com.doverfuelingsolutions.issp.utils.StringUtil
import com.doverfuelingsolutions.issp.utils.WindowUtil
import com.doverfuelingsolutions.issp.utils.log.DFSLog
import com.doverfuelingsolutions.issp.utils.sp.SPKeys
import com.doverfuelingsolutions.issp.utils.sp.SPUtil
import com.doverfuelingsolutions.issp.view.fragment.FragmentPreference
import kotlinx.coroutines.launch

class PreferenceActivity : AppCompatActivity(),
    View.OnClickListener {

    companion object {

        const val codeRequestResult = 1001
        const val isMiddleModified = "isMiddleModified"
        const val isFuelModified = "isFuelModified"

        fun start(context: Context) {
            Intent(context, PreferenceActivity::class.java).let { context.startActivity(it) }
        }

        fun startForResult(activity: Activity) {
            Intent(activity, PreferenceActivity::class.java).let {
                it.putExtra("forResult", true)
                activity.startActivityForResult(it, codeRequestResult)
            }
        }
    }

    private val binding: ActivityPreferenceBinding by lazy {
        DataBindingUtil.setContentView(this, R.layout.activity_preference)
    }
    private val viewModel = PreferenceViewModel()

    private var isForResult = false
    private var oldMiddleInfo = ""
    private var oldFuelInfo = ""
    private var oldSystemInfo = ""

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        supportActionBar?.hide()
        binding.lifecycleOwner = this
        binding.viewModel = viewModel
        binding.handler = this
        if (savedInstanceState == null) {
            supportFragmentManager
                .beginTransaction()
                .replace(R.id.container, FragmentPreference())
                .commit()
        }

        val forResult = intent.getBooleanExtra("forResult", false)
        if (forResult) {
            isForResult = true
            oldMiddleInfo = makeMiddleInfo()
            oldFuelInfo = makeFuelInfo()
            oldSystemInfo = makeSystemInfo()
        } else {
            isForResult = false
        }
    }

    override fun onResume() {
        super.onResume()

        WindowUtil.setFullscreen(this)
    }

    override fun onBackPressed() {
        val hasMiddleModified = makeMiddleInfo() != oldMiddleInfo
        val hasFuelModified = makeFuelInfo() != oldFuelInfo
        val hasSystemModified = makeSystemInfo() != oldSystemInfo
        if (hasSystemModified) SystemApi.regenerateAllService()
        if (hasFuelModified) FuelInfoApi.generateService()
        if (isForResult) {
            setResult(Activity.RESULT_OK, Intent().apply {
                putExtra(isMiddleModified, hasMiddleModified)
                putExtra(isFuelModified, hasFuelModified)
            })
            finish()
        } else {
            super.onBackPressed()
        }
    }

    override fun onClick(v: View?) {
        when (v) {
            binding.checkUpdate -> {
                processUpdate()
            }
            binding.buttonClose -> {
                onBackPressed()
            }
        }
    }

    private fun makeMiddleInfo(): String {
        return "${SPUtil.getString(SPKeys.MIDDLE_IP)}, ${SPUtil.getString(SPKeys.MIDDLE_PORT)}, ${SPUtil.getString(
            SPKeys.MIDDLE_WORKSTATION_ID
        )}"
    }

    private fun makeFuelInfo(): String {
        return "${SPUtil.getString(SPKeys.FUEL_IP)}, ${SPUtil.getString(SPKeys.FUEL_PORT)}"
    }

    private fun makeSystemInfo(): String {
        return "${SPUtil.getString(SPKeys.SERVER_DOMAIN)}, ${SPUtil.getString(SPKeys.SERVER_PORT_CONFIG)}, ${SPUtil.getString(
            SPKeys.SERVER_PORT_BASE
        )}, ${SPUtil.getString(SPKeys.SERVER_PORT_TRX)}, ${SPUtil.getString(SPKeys.SERVER_PORT_ASSETS)}"
    }

    private fun processUpdate() {
        lifecycleScope.launch {
            val currentVersion = AppUtil.getVersionName()
            DFSLog.i("current version is $currentVersion")

            viewModel.isSubmitting.value = true
            val result = SystemApi.remoteVersion()
            viewModel.isSubmitting.value = false

            if (!result.success || result.data == null) {
                DFSLog.e("latest version check failed: ${result.message}")
                DFSToastUtil.fail(StringUtil.get(R.string.fail_behave_reason, StringUtil.get(R.string.check_update), result.message))
                return@launch
            }

            if (result.data.versionList.isEmpty()) {
                DFSLog.e("check version update: no update")
                DFSToastUtil.fail(R.string.no_update_version)
                return@launch
            }

            val remoteVersion = result.data.versionList.last()
            val compare = AppUtil.compareVersion(remoteVersion.version, currentVersion)
            if (compare <= 0) {
                DFSLog.i("latest version check: ${remoteVersion.version}")
                DFSToastUtil.fail(R.string.current_version_is_latest)
                return@launch
            }

            UpdateActivity.start(this@PreferenceActivity, remoteVersion.version, remoteVersion.name, remoteVersion.info)
        }
    }

    class PreferenceViewModel : ViewModel() {
        val isSubmitting = MutableLiveData(false)
    }
}