package com.sambath.sbc.app

import android.annotation.SuppressLint
import android.content.DialogInterface
import android.content.Intent
import android.graphics.Color
import android.os.Bundle
import android.os.CountDownTimer
import android.util.Log
import android.view.MenuInflater
import android.view.View
import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.app.AlertDialog
import androidx.appcompat.widget.PopupMenu
import androidx.constraintlayout.widget.Group
import androidx.core.view.isVisible
import androidx.lifecycle.Observer
import com.cocking.fight.screen.dialogfragment.StatementDialogFragment
import com.google.gson.Gson
import com.sambath.sbc.R
import com.sambath.sbc.base.AutoLogoutBaseActivity
import com.sambath.sbc.remote.ChannelData
import com.sambath.sbc.remote.K
import com.sambath.sbc.remote.User
import com.sambath.sbc.remote.service.ConnectivityStates
import com.sambath.sbc.screen.login.LoginActivity
import com.sambath.sbc.screen.main.MainFragment
import com.sambath.sbc.screen.main.MainViewModel
import com.sambath.sbc.screen.splash.SplashScreenActivity
import com.sambath.sbc.util.Const
import com.sambath.sbc.util.ModelPreferencesManager
import com.sambath.sbc.util.PrefHelper
import com.squareup.moshi.JsonAdapter
import com.squareup.moshi.Moshi
import kotlinx.android.synthetic.main.app_bar.*
import kotlinx.android.synthetic.main.content_main.*
import org.json.JSONObject


class ShareActivity : AutoLogoutBaseActivity() {
    lateinit var settingImageView: ImageView
    lateinit var reportImageView: ImageView
    private val gson = Gson()

    //    lateinit var soundImageView: ImageView
    lateinit var userNameTextView: TextView
    lateinit var balanceTextView: TextView
    lateinit var refreshImageView: ImageView
    private lateinit var moshi: Moshi

    //    private lateinit var remoteConfig: FirebaseRemoteConfig
    lateinit var groupToolbarIcons: Group
    lateinit var sharePref: PrefHelper
    lateinit var layCfStatus: LinearLayout
    lateinit var userShare: User
    private var isOpen: String = "null"
    private val shareViewModel = App.injectShareViewModel()
    private lateinit var mainViewModel: MainViewModel
    override fun onCreate(savedInstanceState: Bundle?) {
//        Log.d("Oncreate", "before")
        moshi = Moshi.Builder().build()
        mainViewModel = MainViewModel(App.injectApiService(), App.injectPrefHelper())
        ModelPreferencesManager.get<User>(Const.USER_KEY)?.let {
            userShare = it
        }
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        val balance = currencyFormat(userShare.accountBalances)
        when (userShare.currencyType) {
            1 -> {//dollar
                tv_amount.text = "$balance $"
            }
            2 -> {//riel
                tv_amount.text ="$balance ៛"
            }
            3 -> {//baht
                tv_amount.text = "$balance ฿"
            }
        }
        tv_user_id.text = userShare.userName
        sharePref = App.injectPrefHelper()
        mtxt_switch_channel.text = "CH" + sharePref.getChannelType()
        txtStatus.text = "Status " + sharePref.getChannelType()
        mainViewModel.getChannel()
        mainViewModel.getUser()
        mainViewModel.getCfResuleData()
        mainViewModel.stateChannel.observe(this, androidx.lifecycle.Observer {
            Log.d("stateChannel", it.toString())
            if (it?.isChSuccess == true) {
                it.channelInfo?.let { it1 -> getChannelData(it1) }
            }
        })
        mainViewModel.stateUser.observe(this, androidx.lifecycle.Observer {
            Log.d("stateUser", it.toString())
            if (it?.isUserSuccess == true) {
                it.userInfo?.let { it1 -> getUserInfo(it1) }
            }
        })
        mainViewModel.state.observe(this, androidx.lifecycle.Observer {
            if (it.isSuccess) {
                if (it.resultList.isNullOrEmpty() || isOpen == "true") {
                    txtWinner.text = "None"
                } else {
                    txtWinner.text = it.resultList!![0].name
                }
            }
        })
//        mainViewModel.getMainData()
        //Log.d("Oncreate", "after")
        if (savedInstanceState == null) {
            supportFragmentManager.beginTransaction()
                .add(
                    R.id.container,
                    MainFragment().apply {
                        arguments =
                            Bundle().apply {
                                //putInt(InventoryFragment.COM_INTO_ID_KEY,10)
                            }
                    })
                .addToBackStack(null)
                .commit()
        }
        reportImageView = findViewById<ImageView>(R.id.iv_report)
        settingImageView = findViewById<ImageView>(R.id.iv_setting)
        refreshImageView = findViewById<ImageView>(R.id.iv_auto_new)
        layCfStatus = findViewById<LinearLayout>(R.id.layCfStatus)
        groupToolbarIcons = findViewById<Group>(R.id.group_toolbar_icons)
        userNameTextView = findViewById<TextView>(R.id.tv_user_id)
        balanceTextView = findViewById<TextView>(R.id.tv_amount)
        mtxt_switch_channel.setOnClickListener { v ->
            val popup = PopupMenu(this, v)
            val inflater: MenuInflater = popup.menuInflater
            inflater.inflate(R.menu.menu_channel, popup.menu)
            popup.setOnMenuItemClickListener {
                when (it.itemId) {
                    R.id.action_channel_1 -> {
                        sharePref.setChannelType(1)
                        this.recreate()
                    }
                    R.id.action_channel_2 -> {
                        sharePref.setChannelType(2)
                        this.recreate()
                    }
                    R.id.action_channel_3 -> {
                        sharePref.setChannelType(3)
                        this.recreate()
                    }
                    R.id.action_channel_4 -> {
                        sharePref.setChannelType(4)
                        this.recreate()
                    }

                }
                true
            }
            popup.show()
        }
        shareViewModel.getUpdateChannelInfo.observe(this, Observer {
            Log.d("Socket", "getUpdateChannelInfo" + it.toString())
            if (!it.isNullOrEmpty()) {
                val adapter: JsonAdapter<ChannelData> = moshi.adapter(
                    ChannelData::class.java
                )
                val channelDataResponse = adapter.fromJson(it)
                if (channelDataResponse != null) {
                    getChannelData(channelDataResponse)
                }
            }
        })
        shareViewModel.getDefinedResultAndChannel.observe(this, Observer {
            Log.d("Socket", "getDefinedResultAndChannel" + it.toString())
            if (!it.isNullOrEmpty()) {
                val obj = JSONObject(it)
                val resultArr = obj.getJSONArray("objCoResult")
                if (resultArr.length() > 0) {
                    txtWinner.text = resultArr.getJSONObject(0).getString("name")
                } else {
                    txtWinner.text = "None"
                }
            }
        })
        shareViewModel.getUpdateUserInfo.observe(this, Observer {
            Log.d("Socket", "getUpdateUserInfo" + it.toString())
            if (!it.isNullOrEmpty()) {
                val obj = JSONObject(it)
                val balance = currencyFormat(obj.getInt("balance"))
                if (userShare.currencyType == 1){//dollar
                    tv_amount.text = "$$balance"
                }else if(userShare.currencyType == 2){//riel
                    tv_amount.text ="៛$balance"
                }else{//baht
                    tv_amount.text = "฿$balance"
                }
            }
        })
        shareViewModel.getResult.observe(this, Observer {
            Log.d("Socket", "getResult")
            if (!it.isNullOrEmpty()) {
                txtWinner.text = it
            } else {
                txtWinner.text = "None"
            }
        })
    }

    private fun alertMsgLogout() {
        val alertDialog: AlertDialog.Builder = AlertDialog.Builder(this)
        alertDialog.setTitle("Logout Alert!")//for set Title
        alertDialog.setMessage("សូមទំនាក់ទំនងទៅកាន់ភ្នាក់ងាររបស់អ្នក!")// for Message
        val alert = alertDialog.create()
//        alertDialog.setNegativeButton(getString(R.string.ok)) { dialog, id ->
//            timer.cancel()
//            dialog.dismiss()
//            logout()
//        }
        alert.setCanceledOnTouchOutside(false)
        alert.setOnShowListener {
            val timer = object : CountDownTimer(1500, 100) {
                override fun onTick(millisUntilFinished: Long) {

                }

                override fun onFinish() {
                    alert.dismiss()
                    logout()
                }
            }
            timer.start()
        }
        alert.show()
        val negativeButton = alert.getButton(DialogInterface.BUTTON_NEGATIVE)
        negativeButton.setTextColor(Color.RED)
    }

    private fun logout() {
        sharePref.logout()
        val intent = Intent(this, LoginActivity::class.java)
        startActivity(intent)
        finishAffinity()
    }

    override fun onWindowFocusChanged(hasFocus: Boolean) {
        super.onWindowFocusChanged(hasFocus)
        //Log.d("Window", "hase focus")
        if (hasFocus) hideSystemUI()
    }

    private fun getUserInfo(it: User) {
        Log.d("stateUser", it.toString())
        tv_amount.text = it.accountBalances?.let { it1 ->
            val balance = currencyFormat(it1)
            if (userShare.currencyType == 1){//dollar
                 "$$balance"
            }else if(userShare.currencyType == 2){//riel
                "៛$balance"
            }else{//baht
                "฿$balance"
            }

        }
        btnBettingStatus.isActivated = true
    }

    private fun getChannelData(it: ChannelData) {
        Log.d("statechannel", it.toString())
//        if (!it.enable) {
//            Log.d("Socket", "enable false")
//            alertMsgLogout()
//        }
        shareViewModel.setChannelInfo(it)
        txtFightNo.text = it.fightNo.toString()
        isOpen = it.is_open.toString()
        btnBettingStatus.isActivated = true
        when (isOpen) {
            "null" -> {
                btnBettingStatus.text = K.Live
                btnBettingStatus.isEnabled = false
                btnBettingStatus.isActivated = false
            }
            "true" -> {
                txtWinner.text = "None"
                btnBettingStatus.text = K.Open
                btnBettingStatus.isEnabled = true
            }
            "false" -> {
                btnBettingStatus.text = K.Close
                btnBettingStatus.isEnabled = false
            }
        }
        shareViewModel.getConnectivityStates.observe(this, Observer {
            getSocketConnectionStatus(it)
        })
    }

    private fun hideSystemUI() {
        window.decorView.systemUiVisibility = (View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY
                // Set the content to appear under the system bars so that the
                // content doesn't resize when the system bars hide and show.
                or View.SYSTEM_UI_FLAG_LAYOUT_STABLE
                or View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
                or View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                // Hide the nav bar and status bar
                or View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
                or View.SYSTEM_UI_FLAG_FULLSCREEN)
    }

    private fun getSocketConnectionStatus(status: Int) {
        when (status) {
            ConnectivityStates.STATE_DISCONNECTED -> {
                Log.d("Socket", "onDisconnect...")
                val mStartActivity = Intent(this, SplashScreenActivity::class.java)
                startActivity(mStartActivity)
                System.exit(0)
            }
            ConnectivityStates.STATE_NOT_CONNECTED -> {
                Log.d("Socket", "onNotconnected...")
                Toast.makeText(this, "មិនអាចភ្ជាប់ទៅកាន់ម៉ាស៊ីនមេ!", Toast.LENGTH_LONG).show()
            }
            ConnectivityStates.STATE_RECONNECTING -> {
                Log.d("Socket", "onReconnecting...")
            }
            ConnectivityStates.STATE_TIMEOUT -> {
                Log.d("Socket", "onTimout...")
                val intent = Intent(this, SplashScreenActivity::class.java)
                startActivity(intent)
                finishAffinity()
            }
            ConnectivityStates.STATE_CONNECTED -> {
                Log.d("Socket", "onConnected...")
//                shareViewModel.remoteMainScreenAPI(userId = user.id)
            }
        }

    }

    override fun onBackPressed() {
        when (supportFragmentManager.backStackEntryCount) {
            1 -> {
                finish()
            }
            else -> {
                groupToolbarIcons.isVisible = true
                layCfStatus.isVisible = true
                super.onBackPressed()
            }
        }
    }

    override fun onDestroy() {
        // App.onAppStop()
        super.onDestroy()
        Log.d("Lifecycle", "onDestroy")
    }

    private var confirmDialog: AlertDialog? = null

    override fun onPause() {
        super.onPause()
        App.onAppStop()
        //Log.d("Lifecycle","onPause")
    }

    override fun onResume() {
        super.onResume()
        App.onStartSocket(sharePref.getToken(), sharePref.getChannelType())//userID = userShare.id)
    }

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

}
