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

class MainFragment : BaseFragment(R.layout.layout_fragment_main_yuki) {
    private val shareViewModel = App.injectShareViewModel()
    private val sharePref = App.injectPrefHelper()
    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()
                }
            }
        }

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

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

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

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

