package com.khmer9.kdmain.screen.main

import android.annotation.SuppressLint
import android.content.Intent
import android.media.MediaPlayer
import android.os.Bundle
import android.util.Log
import android.view.View
import android.widget.Toast
import androidx.lifecycle.Observer
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.khmer9.kdmain.R
import com.khmer9.kdmain.adapter.MainModuleAdapter
import com.khmer9.kdmain.app.App
import com.khmer9.kdmain.app.DownloadController
import com.khmer9.kdmain.app.ShareActivity
import com.khmer9.kdmain.base.BaseFragment
import com.khmer9.kdmain.config.Config
import com.khmer9.kdmain.extension.btnClick
import com.khmer9.kdmain.remote.User
import com.khmer9.kdmain.remote.service.ConnectivityStates
import com.khmer9.kdmain.screen.login.UserViewState
import com.khmer9.kdmain.screen.report.StatementFragment
import com.khmer9.kdmain.screen.setting.SettingFragment
import com.khmer9.kdmain.screen.splash.SplashScreenActivity


class MainFragment : BaseFragment(R.layout.layout_fragment_main_yuki) {
    private val shareViewModel = App.injectShareViewModel()
    private lateinit var user: User
    private lateinit var adapter: MainModuleAdapter
    private lateinit var recyclerView: RecyclerView
    private lateinit var betTouch: MediaPlayer

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        (requireActivity() as ShareActivity).apply {
            user = loginData.user!!
            betTouch = MediaPlayer.create(this, R.raw.bettouch)
        }
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        (requireActivity() as ShareActivity).apply {
            userNameTextView.text = user.userName

            val balance = currencyFormat(user.accountBalances)
            when (user.currencyType) {
                1 -> {//dollar
                    balanceTextView.text = "$balance $"
                }
                2 -> {//riel
                    balanceTextView.text = "$balance ៛"
                }
                3 -> {//baht
                    balanceTextView.text = "$balance ฿"
                }
            }

            reportImageView.setOnClickListener {
                if (!sharePref.getIsMute()) betTouch.start()
                it.btnClick().subscribe {
                    supportFragmentManager.beginTransaction()
                        .setCustomAnimations(
                            R.anim.slide_in,
                            R.anim.slide_out,
                            R.anim.slide_in_exit,
                            R.anim.slide_out_exit
                        )
                        .add(R.id.container, StatementFragment().apply {
                            arguments =
                                Bundle().apply {
                                }
                        })
                        .addToBackStack(null)
                        .commit()
                }
            }

            settingImageView.setOnClickListener {
                if (!sharePref.getIsMute()) betTouch.start()
                it.btnClick().subscribe {
                    supportFragmentManager.beginTransaction()
                        .setCustomAnimations(
                            R.anim.slide_in,
                            R.anim.slide_out,
                            R.anim.slide_in_exit,
                            R.anim.slide_out_exit
                        )
                        .add(R.id.container, SettingFragment())
                        .addToBackStack(null)
                        .commit()
                }
            }

            refreshImageView.setOnClickListener {
                shareViewModel.getUser()
            }
        }

        //
        recyclerView = view.findViewById(R.id.rv_main)

        //
        //shareViewModel.getUser()
        shareViewModel.userState.observe(viewLifecycleOwner, Observer {
            setUserBalance(it)
        })
        shareViewModel.remoteMainModule()
        shareViewModel.getMainModuleState.observe(viewLifecycleOwner, Observer {
            setModuleMain(it)
        })

        shareViewModel.getMoudleTokenState.observe(viewLifecycleOwner, Observer {
            (requireActivity() as ShareActivity).apply {
                if (it != null) {
                    if (it.intent != null && it.tokenData != null) {
                        val launchIntent = it.intent
                        launchIntent?.putExtra("token", it.tokenData?.token)
                        startActivity(launchIntent)
                        Log.d("XXXXXXXXXXXXXX", it.tokenData?.token.toString())
                        it.intent = null
                        it.tokenData = null
                    } else if (it.intent == null && it.tokenData != null && it.appId != null) {
                        when (it.appId) {
                            Config.LOTTO_APP_ID -> {
                                doDownload(Config.LOTTO_DOWNLOAD, it.tokenData?.token)
                            }
                            Config.LOTTO_PLUS_APP_ID -> {
                                doDownload(Config.LOTTO_PLUS_DOWNLOAD, it.tokenData?.token)
                            }
                            Config.YUKI_APP_ID -> {
                                doDownload(Config.YUKI_DOWNLOAD, it.tokenData?.token)
                            }
                            Config.APONG_APP_ID -> {
                                doDownload(Config.APONG_DOWNLOAD, it.tokenData?.token)
                            }
                            Config.COCK_FIGHT_APP_ID -> {
                                doDownload(Config.COCK_FIGHT_DOWNLOAD, it.tokenData?.token)
                            }
                        }

                        it.intent = null
                        it.tokenData = null
                        it.appId = null
                    }
                }
            }
        })
    }

    private fun setUserBalance(state: UserViewState) {
        if (state.user != null) {
            (requireActivity() as ShareActivity).apply {
                val user = state.user
                val balance = currencyFormat(user.accountBalances)
                when (user.currencyType) {
                    1 -> {//dollar
                        balanceTextView.text = "$balance $"
                    }
                    2 -> {//riel
                        balanceTextView.text = "$balance ៛"
                    }
                    3 -> {//baht
                        balanceTextView.text = "$balance ฿"
                    }
                }
            }
        }
    }

    private fun setModuleMain(state: ResultMainState) {
        if (state.resultList != null) {
            adapter = MainModuleAdapter()
            adapter.submitList(state.resultList)
            recyclerView.setHasFixedSize(true)
            recyclerView.layoutManager = LinearLayoutManager(context)
            recyclerView.adapter = adapter

            adapter.detailButtonListener = { id, appId, sub ->
                if (!id.isNullOrEmpty()) {
                    Log.d("MainModuleClick", id + "-" + appId + "-" + sub)
                    if (sub > 1) {
                        (requireActivity() as ShareActivity).apply {
                            supportFragmentManager.beginTransaction()
                                .setCustomAnimations(
                                    R.anim.slide_in,
                                    R.anim.slide_out,
                                    R.anim.slide_in_exit,
                                    R.anim.slide_out_exit
                                )
                                .add(R.id.container, SubModuleFragment().apply {
                                    arguments = Bundle().apply {
                                        putString("module_id", id)
                                    }
                                })
                                .addToBackStack("MainFragment")
                                .commit()
                        }
                    } else {
                        when (appId) {
                            Config.YUKI_APP_ID -> {
                                (requireActivity() as ShareActivity).apply {
                                    val launchIntent = packageManager.getLaunchIntentForPackage(Config.YUKI_PACKAGE)
                                    if (launchIntent != null) {
                                        //launch
                                        shareViewModel.getModuleToken(appId, launchIntent)
                                    } else {
                                        //installed
                                        shareViewModel.getModuleToken(appId, null)
                                        //doDownload(YUKI_DOWNLOAD)
                                    }
                                }
                            }
                            Config.COCK_FIGHT_APP_ID -> {
                                (requireActivity() as ShareActivity).apply {
                                    val launchIntent = packageManager.getLaunchIntentForPackage(Config.COCK_FIGHT_PACKAGE)
                                    if (launchIntent != null) {
                                        shareViewModel.getModuleToken(appId, launchIntent)
                                    } else {
                                        //doDownload(COCK_FIGHT_DOWNLOAD)
                                        shareViewModel.getModuleToken(appId, null)
                                    }
                                }
                            }
                            Config.APONG_APP_ID -> {
                                (requireActivity() as ShareActivity).apply {
                                    val launchIntent = packageManager.getLaunchIntentForPackage(Config.APONG_PACKAGE)
                                    if (launchIntent != null) {
                                        shareViewModel.getModuleToken(appId, launchIntent)
                                    } else {
                                        //doDownload(APONG_DOWNLOAD)
                                        shareViewModel.getModuleToken(appId, null)
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    }

    private fun doDownload(url: String, token: String? = null) {
        try {
            (requireActivity() as ShareActivity).apply {
                downloadController = DownloadController(this, url, token)
                checkStoragePermission()
            }

        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    @SuppressLint("CheckResult")
    override fun onActivityCreated(savedInstanceState: Bundle?) {
        super.onActivityCreated(savedInstanceState)
    }

    override fun onDestroyView() {
        super.onDestroyView()
    }

    override fun onResume() {
        super.onResume()
        shareViewModel.getUser()
    }

    private fun getSocketConnectionStatus(status: Int) {
        when (status) {
            ConnectivityStates.STATE_DISCONNECTED -> {
                Log.d("Socket", "onDisconnect...")

                val mStartActivity = Intent(requireContext(), SplashScreenActivity::class.java)
                startActivity(mStartActivity)
                System.exit(0)
            }
            ConnectivityStates.STATE_NOT_CONNECTED -> {
                Log.d("Socket", "onNotconnected...")
                Toast.makeText(requireContext(), "មិនមាន Internet", Toast.LENGTH_LONG).show()
            }
            ConnectivityStates.STATE_RECONNECTING -> {
                Log.d("Socket", "onReconnecting...")
            }
            ConnectivityStates.STATE_TIMEOUT -> {
                Log.d("Socket", "onTimout...")
                val intent = Intent(requireContext(), SplashScreenActivity::class.java)
                startActivity(intent)
                requireActivity().finishAffinity()
            }
            ConnectivityStates.STATE_CONNECTED -> {
                Log.d("Socket", "onConnected...")
            }
        }
    }
}

