package com.doverfuelingsolutions.issp.view

import android.content.Context
import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.view.View
import androidx.activity.viewModels
import androidx.appcompat.app.AppCompatActivity
import androidx.databinding.DataBindingUtil
import androidx.fragment.app.Fragment
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.lifecycleScope
import com.doverfuelingsolutions.issp.R
import com.doverfuelingsolutions.issp.data.GlobalData
import com.doverfuelingsolutions.issp.databinding.ActivityMainBinding
import com.doverfuelingsolutions.issp.fusion.FusionError
import com.doverfuelingsolutions.issp.fusion.FusionManager
import com.doverfuelingsolutions.issp.fusion.callback.OnFusionEvent
import com.doverfuelingsolutions.issp.utils.ActivityUtil
import com.doverfuelingsolutions.issp.utils.NetworkUtil
import com.doverfuelingsolutions.issp.utils.StringUtil
import com.doverfuelingsolutions.issp.view.fragment.FragmentAction
import com.doverfuelingsolutions.issp.view.fragment.FragmentLoading
import com.doverfuelingsolutions.issp.view.fragment.FragmentSelect
import com.wayne.www.waynelib.fdc.FdcClient
import com.youth.banner.adapter.BannerImageAdapter
import com.youth.banner.holder.BannerImageHolder
import kotlinx.coroutines.launch
import java.io.File

class MainActivity : AppCompatActivity(),
    OnFusionEvent,
    View.OnLongClickListener {

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

    private val binding: ActivityMainBinding by lazy {
        DataBindingUtil.setContentView(
            this,
            R.layout.activity_main
        )
    }
    private val mainViewModel: MainViewModel by viewModels()

    private var isBlockBackPress = false

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding.lifecycleOwner = this
        binding.mainViewModel = mainViewModel
        initView()
        initFusion()
    }

    override fun onResume() {
        super.onResume()
        ActivityUtil.setFullscreen(this)
    }

    override fun onDestroy() {
        super.onDestroy()

        FusionManager.onFusionEvent = null
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)

        lifecycleScope.launch {
            when (requestCode) {
                PreferenceActivity.codeRequestResult -> {
                    data?.let {
                        val isMiddleModified =
                            it.getBooleanExtra(PreferenceActivity.isMiddleModified, false)
                        val isFuelModified =
                            it.getBooleanExtra(PreferenceActivity.isFuelModified, false)
                        if (!isFuelModified && !isMiddleModified) return@let

                        setFragment(FragmentLoading.build(R.string.in_reconnect_fusion))
                        if (isMiddleModified || FusionManager.stateFusion != FdcClient.FdcClientState.Connected) {
                            FusionManager.restart()
                        } else if (isFuelModified && FusionManager.stateFusion == FdcClient.FdcClientState.Connected) {
                            setFragment(FragmentLoading.build(R.string.in_get_fuel))
                            FusionManager.loginFetchInfo()
                        }
                    }
                }
            }
        }
    }

    override fun onBackPressed() {
        if (!isBlockBackPress) super.onBackPressed()
    }

    override fun onLongClick(v: View?): Boolean {
        when (v) {
            binding.clock -> {
                PreferenceActivity.startForResult(this)
            }
        }
        return false
    }

    override fun onFusionInit(code: FusionError, msg: String) {
        lifecycleScope.launch {
            // WrongAddress Timeout 需要修改中控信息，返回时如已修改则重启Fusion
            // GetNozzleInfo 不重启Fusion，重新请求加油信息即可
            when (code) {
                FusionError.Success -> {
                    setFragment(FragmentSelect())
                }
                FusionError.WrongAddress, FusionError.Timeout, FusionError.GetNozzleInfo -> {
                    val buttonText = if (code == FusionError.GetNozzleInfo) {
                        StringUtil.get(R.string.go_check_fuel)
                    } else {
                        StringUtil.get(R.string.go_check_fusion)
                    }
                    setFragment(FragmentAction.build(StringUtil.get(R.string.connect_fail_reason, msg), buttonText) {
                        PreferenceActivity.startForResult(this@MainActivity)
                    })
                }
                FusionError.Login -> {
                    setFragment(FragmentAction.build(StringUtil.get(R.string.connect_fail_reason, msg), StringUtil.get(R.string.retry_login)) {
                        FusionManager.loginFetchInfo()
                    })
                }
            }
        }
    }

    override fun onFusionReconnect() {
        lifecycleScope.launch {
            if (NetworkUtil.isAvailable(this@MainActivity)) {
                FragmentLoading.build(R.string.in_reconnect_fusion)
            } else {
                FragmentLoading.build(R.string.network_error)
            }
        }
    }

    private fun initView() {
        supportActionBar?.hide()
        mainViewModel.stationName.value = GlobalData.businessName.get()
        if (GlobalData.stationLogoFileName.get().isNotEmpty())
            binding.stationLogo.setImageURI(
                Uri.fromFile(
                    File(
                        filesDir,
                        GlobalData.stationLogoFileName.get()
                    )
                )
            )
        binding.banner.run {
            addBannerLifecycleObserver(this@MainActivity)
            scrollTime = 500
            adapter =
                object : BannerImageAdapter<Int>(listOf(R.mipmap.banner_1, R.mipmap.banner_2)) {
                    override fun onBindView(
                        holder: BannerImageHolder,
                        data: Int,
                        position: Int,
                        size: Int
                    ) {
                        holder.imageView.setImageResource(data)
                    }
                }
        }
        binding.clock.setOnLongClickListener(this)

        setFragment(FragmentLoading.build(R.string.in_connect_fusion))
    }

    private fun initFusion() {
        FusionManager.onFusionEvent = this
        lifecycle.addObserver(FusionManager)
    }

    fun setFragment(fragment: Fragment, back: Boolean = false) {
        supportFragmentManager.beginTransaction().run {
            replace(R.id.fragmentBox, fragment)
            if (back) {
                addToBackStack(fragment::class.java.simpleName)
            }
            commit()
        }
    }

    fun backToLogin() {
        LoginActivity.start(this)
        finish()
    }

    fun blockBackPress(isBlock: Boolean) {
        isBlockBackPress = isBlock
    }

    class MainViewModel : ViewModel() {
        val stationName = MutableLiveData("")
    }
}