package com.seatel.mobilehall.ui.base.activity

import android.graphics.Color
import android.os.Build
import android.os.Bundle
import android.text.TextUtils
import android.util.Log
import android.view.MenuItem
import android.view.View
import android.widget.FrameLayout
import android.widget.Toast
import androidx.annotation.LayoutRes
import androidx.appcompat.app.ActionBar
import androidx.core.content.ContextCompat
import com.android.volley.Request
import com.android.volley.VolleyError
import com.google.android.material.snackbar.Snackbar
import com.google.gson.Gson
import com.seatel.mobilehall.R
import com.seatel.mobilehall.data.network.SeatelJSONObjectRequest
import com.seatel.mobilehall.data.prefs.SeatelSharePreferences
import com.seatel.mobilehall.ui.application.MyApplication
import com.seatel.mobilehall.ui.base.interactor.RegisterPushTokenInteractor
import com.seatel.mobilehall.ui.base.presenter.RegisterPushTokenPresenter
import com.seatel.mobilehall.ui.login.model.ProfileModel
import com.seatel.mobilehall.ui.main.MainActivity
import com.seatel.mobilehall.util.Constant
import com.seatel.mobilehall.util.SeatelUtils.Companion.checkPhone
import com.seatel.mobilehall.util.lang.MyContextWrapper
import kotlinx.android.synthetic.main.activity_base.*
import org.json.JSONObject

abstract class BaseActivity : CoreActivity(), RegisterPushTokenInteractor.View {

    private var mActionBar: ActionBar? = null
    private lateinit var mRegisterPushTokenPresenter: RegisterPushTokenPresenter
    private lateinit var mRegisterPushTokenView: RegisterPushTokenInteractor.View

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        super.setContentView(R.layout.activity_base)
    }

    override fun setContentView(@LayoutRes layoutResID: Int) {
        val view = layoutInflater.inflate(layoutResID, null, false)
        content_view!!.addView(view)
        setupToolbar()
        setStatusBarColor()
        initView()
    }

    override fun onOptionsItemSelected(item: MenuItem): Boolean {
        val id = item.itemId
        if (id == android.R.id.home) {
            onBackPressed()
        }
        return super.onOptionsItemSelected(item)
    }

    override fun onBackPressed() {
        if (root_progress != null) {
            if (root_progress.visibility == View.VISIBLE) {
                hideProgress()
                onBackClick()
            } else {
                super.onBackPressed()
            }
        } else {
            super.onBackPressed()
        }
    }

    override fun onResume() {
        super.onResume()
        MyApplication.flagAppResume = true
        if (!MyApplication.appRunning) {
//            Log.i("Detect App", javaClass.simpleName + "****************** onResume")
            postAppUsage("connected")
            MyApplication.appRunning = true
        }
        MyApplication.flagAppResumeFirst++
    }

    override fun onStop() {
        super.onStop()
        if (!MyApplication.flagAppResume || MyApplication.flagAppResumeFirst == 0) {
//            Log.i("Detect App", javaClass.simpleName + "****************** onStop")
            postAppUsage("disconnected")
            MyApplication.appRunning = false
            MyApplication.flagAppResumeFirst = -1
        }
        MyApplication.flagAppResume = false

    }

    private fun postAppUsage(strStatus: String) {
        object : SeatelJSONObjectRequest(this@BaseActivity) {

            override fun getFunctionName(): String {
                return Constant.APPUSAGES
            }

            override fun onGetBodyRequest(): String {
                val data = JSONObject()
                data.put("phoneNumber", getPhoneLogin())
                data.put("status", strStatus)
                return data.toString()
            }


            override fun getMethod(): Int {
                return Request.Method.POST
            }


        }.execute()
    }

    override fun onInternetConnect() {
        if (!MyApplication.isInternetConnected) {
            MyApplication.isInternetConnected = true
            val snackBar = Snackbar.make(
                window.decorView.findViewById(android.R.id.content),
                getString(R.string.message_connect_internet),
                Snackbar.LENGTH_SHORT
            )
            snackBar.view.setBackgroundColor(ContextCompat.getColor(this, R.color.internet_connect))
            snackBar.show()
        }
    }

    override fun onInternetDisconnect() {
        MyApplication.isInternetConnected = false
        val snackBar = Snackbar.make(
            window.decorView.findViewById(android.R.id.content),
            getString(R.string.message_no_internet),
            Snackbar.LENGTH_INDEFINITE
        )
        snackBar.view.setBackgroundColor(ContextCompat.getColor(this, R.color.internet_disconnect))
        snackBar.show()
    }

    /*Setup Toolbar*/
    private fun setupToolbar() {

        if (toolbar != null) {
            toolbar.visibility = if (isDisplayToolbar()) View.VISIBLE else View.GONE
            view_bg.visibility = if (isDisplayToolbar()) View.VISIBLE else View.GONE
            if (isDisplayToolbar()) {
                view_bg.visibility =
                    if (isDisplayTransparentBackground()) View.GONE else View.VISIBLE
            }
            setSupportActionBar(toolbar)
        }
        try {
            mActionBar = supportActionBar
        } catch (ex: NullPointerException) {
            ex.printStackTrace()
        }

        if (mActionBar != null) {
            mActionBar!!.setDisplayHomeAsUpEnabled(isDisplayHome())
            mActionBar!!.setDisplayShowTitleEnabled(false)
            if (isShowBackButtonLeft()) {
                mActionBar!!.setHomeAsUpIndicator(R.drawable.ic_left_back)
                if (isCancelBackType()) {
                    mActionBar!!.setHomeAsUpIndicator(R.drawable.ic_close_x)
                }
                if (isCancelRigthType()) {
                    mActionBar!!.setHomeAsUpIndicator(0)
                }
            }

            text_view_titleBar!!.visibility = if (isDisplayTitle()) View.VISIBLE else View.GONE
            if (getStringToolbarTitle() == null) {
                text_view_titleBar.text = getToolbarTitle()
            } else {
                text_view_titleBar.text = getStringToolbarTitle()
            }

            image_view_logo!!.visibility = if (isDisplayLogo()) View.VISIBLE else View.GONE

            if (getImageResource() != 0) {
                image_view_logo.setImageResource(getImageResource())
            }
        }
    }

    fun setToolbarTitle(title: String) {
        text_view_titleBar.text = title
    }

    override fun onRegisterPushTokenSucceed(response: JSONObject) {
        SeatelSharePreferences.getInstance(this)?.setRegisterPush(true)
        MyApplication.isPushTokenRegister = 1
    }

    override fun onRegisterPushTokenFailed(error: VolleyError) {
        SeatelSharePreferences.getInstance(this)?.setRegisterPush(false)
    }

    fun onRegisterFirebasePushToken() {
        mRegisterPushTokenView = this
        mRegisterPushTokenPresenter = RegisterPushTokenPresenter(this, mRegisterPushTokenView)
        /* FirebaseInstanceId.getInstance().instanceId.addOnSuccessListener {
             mRegisterPushTokenPresenter.onRegisterPushToken(it.token, getPhoneLogin())
         }*/
    }

    protected open fun getImageResource(): Int {
        return 0
    }

    protected open fun isDisplayBackgroundBlur(): Boolean {
        return false
    }

    protected open fun isDisplayLogo(): Boolean {
        return false
    }

    protected open fun isCancelBackType(): Boolean {
        return false
    }

    protected open fun isCancelRigthType(): Boolean {
        return false
    }

    /*Set toolbar title*/
    protected open fun getToolbarTitle(): String {
        return ""
    }

    /*Set toolbar string title*/
    protected open fun getStringToolbarTitle(): String? {
        return null
    }


    /*Is display home button*/
    protected open fun isDisplayHome(): Boolean {
        return true
    }

    /*Is display title*/
    protected open fun isDisplayTitle(): Boolean {
        return true
    }

    /*Is display toolbar or not*/
    protected open fun isDisplayToolbar(): Boolean {
        return true
    }

    /*Is display toolbar or not*/
    protected open fun isDisplayTransparentBackground(): Boolean {
        return false
    }

    protected open fun isShowBackButtonLeft(): Boolean {
        return true
    }

    /*Action back pressed*/
    protected fun onBackClick() {
        super.onBackPressed()
    }

    /*Show toast*/
    protected fun showToast(msg: String) {
        Toast.makeText(this, msg, Toast.LENGTH_LONG).show()
    }

    /*Log debug*/
    protected fun showLog(key: String, value: String) {
        Log.d(key, value)
    }

    /*Show progressbar*/
    fun showProgress() {
        this.root_progress!!.visibility = View.VISIBLE
    }

    /*Hide progressbar*/
    fun hideProgress() {
        this.root_progress!!.visibility = View.GONE
    }

    /*Init component of view for activity*/
    protected fun initView() {}


    /*Get progressbar*/
    protected open fun getProgressbar(): FrameLayout? {
        return this.root_progress
    }

    protected open fun isStatusBarColorDark(): Boolean {
        return false
    }

    fun isLogIn(): Boolean {
        return !TextUtils.isEmpty(SeatelSharePreferences.getInstance(this)?.getAccessToken())
    }

    fun gotoMainScreen() {
        if (SeatelSharePreferences.getInstance(applicationContext)?.getNoneSeatelNumber()!!) {
            //   HomeMainNonSeatelActivity.lunch(applicationContext)
        } else {
            MainActivity.lunch(applicationContext)
            //  HomeMainActivity.lunch(applicationContext)
        }

//        if (SeatelSharePreferences.getConstant(applicationContext).phoneLogin.startsWith("018")
//                || SeatelSharePreferences.getConstant(applicationContext).phoneLogin.startsWith("85518")
//                || SeatelSharePreferences.getConstant(applicationContext).phoneLogin.startsWith("18")) {
//            SeatelSharePreferences.getConstant(applicationContext).noneSeatelNumber = false
//            HomeMainActivity.lunch(applicationContext)
//        } else {
//            SeatelSharePreferences.getConstant(applicationContext).noneSeatelNumber = true
//            HomeMainNonSeatelActivity.lunch(applicationContext)
//        }
    }

    fun getPhoneLogin(): String {
        return SeatelSharePreferences.getInstance(this)?.getPhoneLogin()!!
    }

    fun isNoneSeatel(): Boolean {
        return SeatelSharePreferences.getInstance(this)?.getNoneSeatelNumber()!!
    }

    fun isPostPaidAccount(): Boolean {
        return SeatelSharePreferences.getInstance(this)?.getIsPostPaid()!!
    }

    fun getMainPhoneLogin(): String {
        return SeatelSharePreferences.getInstance(this)?.getMainPhoneLogin()!!
    }

    fun getProfile(): ProfileModel {
        return if (!TextUtils.isEmpty(SeatelSharePreferences.getInstance(this)?.getUserInfo()))
            Gson().fromJson(
                SeatelSharePreferences.getInstance(this)?.getUserInfo(),
                ProfileModel::class.java
            )
        else ProfileModel()
    }

    fun isMainAccountLogin(): Boolean {
        if (TextUtils.equals(
                checkPhone(getPhoneLogin()),
                checkPhone(getMainPhoneLogin())
            )
        )
            return true
        return false
    }

    fun getPasswordLogin(): String {
        return SeatelSharePreferences.getInstance(this)?.getPasswordLogin()!!
    }

    open fun getHeight(height: View): Int {
        return height.height
    }

    open fun changeLocalLang(langCode: String) {
        MyContextWrapper.wrap(this, langCode)
    }

    /*Set status bar color*/
    private fun setStatusBarColor() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            val window = this.window
            if (isStatusBarColorDark()) {
                window.decorView.systemUiVisibility =
                    View.SYSTEM_UI_FLAG_LAYOUT_STABLE or View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN or View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR
            } else {
                window.decorView.systemUiVisibility =
                    View.SYSTEM_UI_FLAG_LAYOUT_STABLE or View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
            }
            window.statusBarColor = Color.TRANSPARENT

        }
    }


    fun activityEnterFadeInAnimation() {
        overridePendingTransition(R.anim.activity_fade_in, R.anim.activity_hold)
    }

    fun activityExitFadeOutAnimation() {
        overridePendingTransition(R.anim.activity_hold, R.anim.activity_fade_out)
    }

    fun activityEnterUpAnimation() {
        overridePendingTransition(R.anim.activity_slide_up, R.anim.activity_hold)
    }

    fun activityExitDownAnimation() {
        overridePendingTransition(R.anim.activity_hold, R.anim.activity_slide_down)
    }

    fun activityEnterRightAnimation() {
        overridePendingTransition(R.anim.activity_slide_in_right, R.anim.activity_slide_out_left)
    }

    fun activityExitLeftAnimation() {
        overridePendingTransition(R.anim.activity_slide_in_left, R.anim.activity_slide_out_right)
    }
}