package com.sambath.klaklouk_main.app

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.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.google.gson.Gson
import com.sambath.klaklouk_main.R
import com.sambath.klaklouk_main.base.AutoLogoutBaseActivity
import com.sambath.klaklouk_main.remote.ChannelData
import com.sambath.klaklouk_main.remote.K
import com.sambath.klaklouk_main.remote.User
import com.sambath.klaklouk_main.remote.UserInformation
import com.sambath.klaklouk_main.remote.service.ConnectivityStates
import com.sambath.klaklouk_main.screen.login.LoginActivity
import com.sambath.klaklouk_main.screen.main.MainFragment
import com.sambath.klaklouk_main.screen.main.MainViewModel
import com.sambath.klaklouk_main.screen.splash.SplashScreenActivity
import com.sambath.klaklouk_main.util.Const
import com.sambath.klaklouk_main.util.ModelPreferencesManager
import com.sambath.klaklouk_main.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 userNameTextView: TextView
    lateinit var balanceTextView: TextView
    lateinit var refreshImageView: ImageView
    private lateinit var moshi: Moshi

    lateinit var groupToolbarIcons: Group
    lateinit var sharePref: PrefHelper
    lateinit var layCfStatus: LinearLayout
    lateinit var userShare: User
    private var isOpen: String = "null"
    private var chName: String = ""
    private var chList: List<Int> = mutableListOf()
    private val shareViewModel = App.injectShareViewModel()
    private lateinit var mainViewModel: MainViewModel

    override fun onCreate(savedInstanceState: Bundle?) {
        moshi = Moshi.Builder().build()
        mainViewModel = MainViewModel(App.injectApiService(), App.injectPrefHelper())
        ModelPreferencesManager.getUser(Const.USER_KEY)?.let {
            userShare = it
            Log.d("loginget<User>", it.toString())
        }
        ModelPreferencesManager.getChannelList(Const.CH_LIST_KEY)?.let {
            Log.d("getChanneList", it.toString())
            chList = it
        }
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        sharePref = App.injectPrefHelper()
        if (userShare.isSuspend) {
            logout()
        }
        val balance = currencyFormat(userShare.accountBalances.toString())
        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
        linBetTie.visibility = View.GONE
        chName = when (sharePref.getChannelType()) {
            1 -> {
                "PH"
            }
            4 -> {
                "KD"
            }
            else -> {
                "CH" + sharePref.getChannelType()
            }
        }
        mtxt_switch_channel.text = chName
        txtStatus.text = "Status $chName"
        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 ->
                    if (it1.isSuspend) {
                        logout()
                    }
                    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
                }
            }
        })
        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)
            for (channel in chList) { // "limits" its an arraylist
                val chName = when (channel) {
                    1 -> {
                        "PH"
                    }
                    4 -> {
                        "KD"
                    }
                    else -> {
                        "CH$channel"
                    }
                }
                popup.menu.add(0, channel, 0, chName)
            }
            popup.setOnMenuItemClickListener(PopupMenu.OnMenuItemClickListener { item ->
                if (sharePref.getChannelType() != item.itemId) {
                    sharePref.setChannelType(item.itemId)
                    this.recreate()
                }
                false
            })
            popup.show()
        }
        shareViewModel.getStartCountDown.observe(this, Observer {
            if (!it.isNullOrEmpty()) {
                val obj = JSONObject(it)
                var countDown = obj.getInt(K.CountDown)
                var type = obj.getString(K.Type)

                btnBettingTime.text = countDown.toString()

                if (type.equals(K.Close, ignoreCase = true)) {
                    btnBettingStatus.text = K.Close
                    btnBettingStatus.isEnabled = false
                } else if (type.equals(K.Open, ignoreCase = true)) {
                    btnBettingStatus.text = K.Open
                    btnBettingStatus.isEnabled = true
                }
            }
        })
        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 isSuspend = obj.getBoolean("is_suspend")
                if (isSuspend) {
                    shareViewModel.resetUserInfo()
                    logout()
                } else {
                    userShare.readOnly = obj.getBoolean("is_suspend")
                    userShare.accountBalances = obj.getString("balance")
                    userShare.isSuspend = isSuspend
                    ModelPreferencesManager.putUser(userShare, Const.USER_KEY)
                    val balance = currencyFormat(obj.getDouble("balance"))
                    when (userShare.currencyType) {
                        1 -> {//dollar
                            tv_amount.text = "$$balance"
                        }
                        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()
        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: UserInformation) {
        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"
            }
        }
        userShare.readOnly = it.readOnly
        userShare.isSuspend = it.isSuspend
        userShare.accountBalances = it.accountBalances.toString()
        ModelPreferencesManager.putUser(userShare, Const.USER_KEY)
        btnBettingStatus.isActivated = true
    }

    private fun getChannelData(it: ChannelData) {
        Log.d("statechannel", it.toString())
        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 -> {
                linBetTie.visibility = View.GONE
                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()
    }

}
