package com.mobiuz.app.dev

import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.os.Bundle
import android.view.View
import androidx.appcompat.app.AppCompatActivity
import androidx.core.os.bundleOf
import androidx.core.view.isVisible
import androidx.navigation.NavController
import androidx.navigation.fragment.NavHostFragment
import com.mobiuz.app.R
import com.mobiuz.app.databinding.ActivityOfflineBinding
import com.mobiuz.app.dev.model.SharedPref
import com.mobiuz.app.dev.ui.auth.AuthActivity
import com.mobiuz.app.dev.ui.global.CONSTANTS
import com.mobiuz.app.dev.ui.service.ServiceAdapter
import com.mobiuz.app.dev.utils.LocaleHelper
import com.mobiuz.app.dev.utils.NetworkUtil
import com.mobiuz.app.dev.utils.extensions.customLog
import com.mobiuz.app.dev.utils.extensions.showMessage
import dagger.hilt.android.AndroidEntryPoint
import javax.inject.Inject


@AndroidEntryPoint
class OfflineActivity : AppCompatActivity() {

    private var _bn: ActivityOfflineBinding? = null
    private val bn get() = _bn ?: throw NullPointerException("cannot inflate")
    private lateinit var adapter: ServiceAdapter
    private lateinit var navController: NavController
    private lateinit var receiver: BroadcastReceiver
    private val intentFilter = IntentFilter()

    // if offline type == 0
    private var type = 0

    @Inject
    lateinit var pref: SharedPref

    override fun onCreate(savedInstanceState: Bundle?) {
        LocaleHelper.setLocale(this)
        super.onCreate(savedInstanceState)
        _bn = ActivityOfflineBinding.inflate(layoutInflater)
        setContentView(bn.root)
        window.decorView.systemUiVisibility = window.decorView.systemUiVisibility or View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR
        adapter = ServiceAdapter(pref.language)
        pref.isShowPin = false

        val fragment = supportFragmentManager.findFragmentById(R.id.offline_container) as NavHostFragment
        navController = NavHostFragment.findNavController(fragment)
//        if(intent )

        intent?.let {
            val type = it.getStringExtra(CONSTANTS.TYPE_SERVICE)
            navController.popBackStack()

            if (pref.isRegistered && pref.pinCode.isNotEmpty() && type != CONSTANTS.FROM_ONLINE) {
                navController.navigate(R.id.fullScreenFragment, bundleOf(CONSTANTS.TYPE_PIN to CONSTANTS.OFFLINE))
            } else {
                navController.navigate(R.id.serviceFragment, bundleOf(CONSTANTS.TYPE_SERVICE to CONSTANTS.OFFLINE))
            }
        }



        receiver = object : BroadcastReceiver() {
            override fun onReceive(context: Context?, intent: Intent?) {
                if (intent?.action == CONSTANTS.USSD_ACTION_REFRESH) {
                   pref.blockedTime = System.currentTimeMillis()
                    customLog("USSD_ACTION_REFRESH")
                }
                if (intent?.action == CONSTANTS.CONNECTIVITY_CHANGE) {
                    sendBroadcast(Intent(CONSTANTS.MY_CONNECTIVITY_CHANGE))
                }
                if (intent?.action == CONSTANTS.MY_CONNECTIVITY_CHANGE) {
                    type = NetworkUtil.getConnectivityStatus(this@OfflineActivity)
                    bn.btnTryAgain.isVisible = (type != 0) && (navController.currentDestination?.id != R.id.fullScreenFragment)
                    if (type != 0) {
                        showMessage(getString(R.string.yes_internet_connect))
                    }
                }

            }
        }

        intentFilter.addAction(CONSTANTS.CONNECTIVITY_CHANGE)
        intentFilter.addAction(CONSTANTS.MY_CONNECTIVITY_CHANGE)
        intentFilter.addAction(CONSTANTS.USSD_ACTION_REFRESH)
        registerReceiver(receiver, intentFilter)

        bn.btnTryAgain.setOnClickListener {
            if (type != 0) {
                navigate()
            }
        }

    }

    override fun onResume() {
        super.onResume()
        if (pref.isRegistered && pref.isShowPin && pref.pinCode.isNotEmpty()) {
            showPinCode()
        } else {
            pref.blockedTime = System.currentTimeMillis()
            pref.isShowPin = true
        }
    }

    override fun onStop() {
        super.onStop()
        pref.blockedTime = System.currentTimeMillis()
    }


    private fun showPinCode() {
        if (pref.blockedTime < System.currentTimeMillis() - CONSTANTS.BLOCKED_TIME) {
            if (navController.currentDestination?.id != R.id.fullScreenFragment &&
                navController.currentDestination?.id != R.id.ussdFragment) {
                customLog("fullScreenFragment")
                bn.btnTryAgain.isVisible = false
                navController.navigate(R.id.fullScreenFragment, bundleOf(CONSTANTS.TYPE_PIN to CONSTANTS.TYPE_AFTER))
            }
        }

    }

    fun navigate() {
        when {
            !pref.isRegistered -> {
                startActivity(Intent(this, AuthActivity::class.java))
            }

            pref.pinCode.isEmpty() -> {
                startActivity(Intent(this, AuthActivity::class.java).putExtra(CONSTANTS.TYPE_AUTH, CONSTANTS.PIN_CODE))
            }

            else -> {
                val intent = Intent(this, MainActivity::class.java)
                intent.putExtra(CONSTANTS.FIRST, CONSTANTS.FIRST)
                intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_TASK_ON_HOME
                startActivity(intent)
            }
        }
        finish()
    }


    override fun onDestroy() {
        unregisterReceiver(receiver)
        _bn = null
        pref.blockedTime = 0
        super.onDestroy()
    }
}