package com.adealink.weparty.ui.home

import android.annotation.SuppressLint
import android.os.Bundle
import android.view.View
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.core.view.updateLayoutParams
import com.adealink.frame.log.Log
import com.adealink.frame.mvvm.view.viewBinding
import com.adealink.frame.router.Router
import com.adealink.frame.startup.DistributedLoadManager
import com.adealink.frame.util.onClick
import com.adealink.weparty.AppModule
import com.adealink.weparty.R
import com.adealink.weparty.commonui.BaseActivity
import com.adealink.weparty.commonui.BaseFragment
import com.adealink.weparty.commonui.ext.show
import com.adealink.weparty.constant.TAG_TIME_APP_START
import com.adealink.weparty.constant.logTime
import com.adealink.weparty.databinding.FragmentHomeBinding
import com.adealink.weparty.module.playmate.Playmate
import com.adealink.weparty.module.profile.Profile
import com.adealink.weparty.module.room.RoomModule
import com.adealink.weparty.module.room.data.createRoomPermissionLD
import com.adealink.weparty.util.applyImmersive
import java.util.LinkedList
import java.util.Queue

class HomeFragment : BaseFragment(R.layout.fragment_home) {

    companion object {
        const val TAG = "HomeFragment"

        fun newInstance(mainTabKey: String?, subTabKey: String?): HomeFragment {
            return HomeFragment().apply {
                arguments = Bundle().apply {
                    putString(AppModule.Main.EXTRA_MAIN_TAB, mainTabKey)
                    putString(AppModule.Main.EXTRA_MAIN_SUB_TAB, subTabKey)
                }
            }
        }
    }

    private val binding by viewBinding(FragmentHomeBinding::bind)
    private lateinit var dlManager: DistributedLoadManager

    @SuppressLint("MissingSuperCall")
    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        logTime(TAG_TIME_APP_START, "HomeFragment.onViewCreated()")
        activity.applyImmersive { top ->
            binding.clTopBar.updateLayoutParams<ConstraintLayout.LayoutParams> {
                topMargin = top
            }
        }
        dlManager = DistributedLoadManager(lifecycle, stepsLoad())
        activity?.let { dlManager.triggerDistributedLoad(it) }
    }

    private fun stepsLoad(): Queue<Runnable> {
        val steps = LinkedList<Runnable>()
        steps.add(Runnable {
            Log.d(TAG, "HomeFragment.step1: initViews, initComponents, observeViewModel")
            initViews()
            initComponents()
            observeViewModel()
        })
        steps.add(Runnable {
            Log.d(TAG, "HomeFragment.step2: loadData")
            loadData()
        })
        return steps
    }

    override fun initViews() {
        super.initViews()
        binding.ivSearch.onClick {
            goSearch()
        }

        RoomModule
        binding.btnCreateHome.onClick {
            createRoom()
        }

        inflatePlaymateHome()
    }

    override fun observeViewModel() {
        super.observeViewModel()
        createRoomPermissionLD.observe(viewLifecycleOwner) {
            binding.btnCreateHome.show(it)
        }
    }

    private fun goSearch() {
        activity?.let { act ->
            Router.build(act, Profile.Search.PATH)
                .start()
        }
    }

    private fun inflatePlaymateHome() {
        var fragment =
            childFragmentManager.findFragmentByTag(Playmate.Home.PATH) as? BaseFragment
        if (fragment?.isAdded == true) {
            return
        }
        fragment = Router.getRouterInstance<BaseFragment>(Playmate.Home.PATH) ?: return
        childFragmentManager.beginTransaction()
            .replace(binding.flContent.id, fragment, "PlaymateHomeList")
            .commitAllowingStateLoss()
    }

    private fun createRoom() {
        val act = (activity as? BaseActivity) ?: return
        RoomModule.createRoom(act)
    }

}