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.StringUtil
import com.doverfuelingsolutions.issp.utils.log.DFSLog
import com.doverfuelingsolutions.issp.view.fragment.FragmentHolder
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 val fragmentHolder = FragmentHolder()
    private val fragmentSelect = FragmentSelect()

    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)

        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(fragmentHolder)
                    if (isMiddleModified || FusionManager.stateFusion != FdcClient.FdcClientState.Connected) {
                        fragmentHolder.loading(StringUtil.get(R.string.in_reconnect_fusion))
                        FusionManager.restart()
                    } else if (isFuelModified && FusionManager.stateFusion == FdcClient.FdcClientState.Connected) {
                        fragmentHolder.loading(StringUtil.get(R.string.in_get_fuel))
                        FusionManager.loginFetchInfo()
                    }
                }
            }
        }
    }

    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 -> {
                    setFragment(fragmentHolder)
                    val buttonText = if (code == FusionError.GetNozzleInfo) {
                        StringUtil.get(R.string.go_check_fuel)
                    } else {
                        StringUtil.get(R.string.go_check_fusion)
                    }
                    fragmentHolder.action(StringUtil.get(R.string.connect_fail_reason, msg), buttonText) {
                        PreferenceActivity.startForResult(this@MainActivity)
                    }
                }
                FusionError.Login -> {
                    setFragment(fragmentHolder)
                    fragmentHolder.action(StringUtil.get(R.string.connect_fail_reason, msg), StringUtil.get(R.string.retry_login)) {
                        FusionManager.loginFetchInfo()
                    }
                }
            }
        }
    }

    override fun onFusionReconnect() {
        lifecycleScope.launch {
            setFragment(fragmentHolder)
            fragmentHolder.loading(StringUtil.get(R.string.in_reconnect_fusion))
        }
    }

    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)
    }

    private fun initFusion() {
        setFragment(fragmentHolder)

        FusionManager.onFusionEvent = this
        lifecycle.addObserver(FusionManager)
    }

    private fun setFragment(fragment: Fragment, back: Boolean = false) {
        val contain = supportFragmentManager.fragments.contains(fragment)
        val show = fragment.isHidden

        if (contain && !show) return

        val transaction = supportFragmentManager.beginTransaction()
        supportFragmentManager.fragments.forEach {
            if (fragment != it && !it.isHidden) transaction.hide(it)
        }
        if (!contain) {
            transaction.add(R.id.fragmentBox, fragment)
        } else if (fragment.isHidden) {
            transaction.show(fragment)
        }
        transaction.commit()
    }

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