package com.khmer9.sbcmain.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.sbcmain.R
import com.khmer9.sbcmain.adapter.MainModuleAdapter
import com.khmer9.sbcmain.app.App
import com.khmer9.sbcmain.app.DownloadController
import com.khmer9.sbcmain.app.ShareActivity
import com.khmer9.sbcmain.base.BaseFragment
import com.khmer9.sbcmain.extension.btnClick
import com.khmer9.sbcmain.remote.User
import com.khmer9.sbcmain.remote.service.ConnectivityStates
import com.khmer9.sbcmain.screen.report.StatementFragment
import com.khmer9.sbcmain.screen.setting.SettingFragment
import com.khmer9.sbcmain.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

    private val YUKI_APP_ID = "630478c22983a591133f0492"
    private val YUKI_DOWNLOAD = "https://www.dropbox.com/s/uzvfo7jahmcl8pe/Khmer9_Yuki_devDebug_1.0.1-dev.apk?dl=1"
    private val YUKI_PACKAGE = "com.khmer9.yuki"

    private val LOTTO_APP_ID = ""
    private val LOTTO_DOWNLOAD = ""
    private val LOTTO_PACKAGE = ""

    private val LOTTO_PLUS_APP_ID = ""
    private val LOTTO_PLUS_DOWNLOAD = ""
    private val LOTTO_PLUS_PACKAGE = ""

    private val COCK_FIGHT_APP_ID = ""
    private val COCK_FIGHT_DOWNLOAD = ""
    private val COCK_FIGHT_PACKAGE = ""

    private val APONG_APP_ID = ""
    private val APONG_DOWNLOAD = ""
    private val APONG_PACKAGE = ""

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

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

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

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

    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(null)
                                .commit()
                        }
                    } else {
                        when (appId) {
                            YUKI_APP_ID -> {
                                (requireActivity() as ShareActivity).apply {
                                    val launchIntent = packageManager.getLaunchIntentForPackage(YUKI_PACKAGE)
                                    if (launchIntent != null) {
                                        //launch
                                        shareViewModel.getModuleToken(appId, launchIntent)
                                    } else {
                                        //installed
                                        doDownload(YUKI_DOWNLOAD)
                                    }
                                }
                            }
                            LOTTO_APP_ID -> {
                                (requireActivity() as ShareActivity).apply {
                                    val launchIntent = packageManager.getLaunchIntentForPackage(LOTTO_PACKAGE)
                                    if (launchIntent != null) {
                                        shareViewModel.getModuleToken(appId, launchIntent)
                                    } else {
                                        doDownload(LOTTO_DOWNLOAD)
                                    }
                                }
                            }
                            LOTTO_PLUS_APP_ID -> {
                                (requireActivity() as ShareActivity).apply {
                                    val launchIntent = packageManager.getLaunchIntentForPackage(LOTTO_PLUS_PACKAGE)
                                    if (launchIntent != null) {
                                        shareViewModel.getModuleToken(appId, launchIntent)
                                    } else {
                                        doDownload(LOTTO_PLUS_DOWNLOAD)
                                    }
                                }
                            }
                            COCK_FIGHT_APP_ID -> {
                                (requireActivity() as ShareActivity).apply {
                                    val launchIntent = packageManager.getLaunchIntentForPackage(COCK_FIGHT_PACKAGE)
                                    if (launchIntent != null) {
                                        shareViewModel.getModuleToken(appId, launchIntent)
                                    } else {
                                        doDownload(COCK_FIGHT_DOWNLOAD)
                                    }
                                }
                            }
                            APONG_APP_ID -> {
                                (requireActivity() as ShareActivity).apply {
                                    val launchIntent = packageManager.getLaunchIntentForPackage(APONG_PACKAGE)
                                    if (launchIntent != null) {
                                        shareViewModel.getModuleToken(appId, launchIntent)
                                    } else {
                                        doDownload(APONG_DOWNLOAD)
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    }

    private fun doDownload(url: String) {
        try {
            (requireActivity() as ShareActivity).apply {
                downloadController = DownloadController(this, url)
                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()
    }

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

