package com.seatel.mobilehall.ui.profile.activity

import android.animation.Animator
import android.animation.ObjectAnimator
import android.app.Activity
import android.content.Context
import android.content.Intent
import android.hardware.fingerprint.FingerprintManager
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.os.Handler
import android.util.Log
import android.view.View
import android.view.animation.LinearInterpolator
import android.widget.CompoundButton
import androidx.annotation.RequiresApi
import com.android.volley.VolleyError
import com.facebook.login.LoginManager
import com.seatel.mobilehall.R
import com.seatel.mobilehall.data.network.Devices
import com.seatel.mobilehall.data.prefs.SeatelSharePreferences
import com.seatel.mobilehall.databinding.ActivitySettingBinding
import com.seatel.mobilehall.ui.application.MyApplication
import com.seatel.mobilehall.ui.base.activity.BaseActivity
import com.seatel.mobilehall.ui.login.interactor.UnRegisterPushTokenInteractor
import com.seatel.mobilehall.ui.login.prefs.FingerprintSharePreferences
import com.seatel.mobilehall.ui.login.presenter.UnRegisterPushTokenPresenter
import com.seatel.mobilehall.util.AnalyticsHelper
import com.seatel.mobilehall.util.Constant
import com.seatel.mobilehall.util.SeatelAlertDialog
import com.seatel.mobilehall.util.SeatelUtils
import com.seatel.mobilehall.util.customview.ErrorHandleView
import com.seatel.mobilehall.util.lang.FirstLoginPreference
import com.seatel.mobilehall.util.lang.LanguageManager
import org.json.JSONObject
import java.io.File
import java.util.Locale

class SettingActivity : BaseActivity<ActivitySettingBinding>(), View.OnClickListener,
    CompoundButton.OnCheckedChangeListener, UnRegisterPushTokenInteractor.View {

    private lateinit var mUnRegisterPushTokenPresenter: UnRegisterPushTokenPresenter
    private var mDialogShow: SeatelAlertDialog? = null

    override fun onUnRegisterPushTokenSucceed(response: JSONObject) {
        binding.errorView.visibility = View.GONE
        MyApplication.isPushTokenRegister = 0
    }

    override fun onUnRegisterPushTokenFailed(error: VolleyError) {
        binding.errorView.visibility = View.GONE
    }

    override fun onCheckedChanged(buttonView: CompoundButton?, isChecked: Boolean) {
        // Un Register Push notification action
        if (isChecked) {
            onRegisterFirebasePushToken()
        } else {
            binding.errorView.setViewMode(ErrorHandleView.Mode.LOADING)
            mUnRegisterPushTokenPresenter.onUnRegisterPushToken(getPhoneLogin())
        }
        SeatelSharePreferences.getInstance(this)?.setRegisterPush(isChecked)
    }

    override fun onClick(v: View?) {
        if (v != null) {
            when (v.tag) {
                "CLEAR_CACHE" -> {
                    animateProgressClearCache()
                    AnalyticsHelper.logEvent(
                        AnalyticsHelper.Event.SETTING_TAP_CLEAR_CACHE,
                        null
                    )
                }

                "LANGUAGE" -> {
                    SettingLanguageActivity.lunch(
                        this,
                        Constant.REQUEST_CHANGE_LANGUAGE_CODE
                    )
                    AnalyticsHelper.logEvent(
                        AnalyticsHelper.Event.SETTING_TAP_LANGUAGE,
                        null
                    )
                }

                "APP_VERSION" -> {
                    gotoPlayStore()
                    AnalyticsHelper.logEvent(
                        AnalyticsHelper.Event.SETTING_TAP_APP_VERSION,
                        null
                    )
                }

                "FINGERPRINT" -> {
                    AnalyticsHelper.logEvent(
                        AnalyticsHelper.Event.SETTING_TAP_ENABLE_FACE_ID,
                        null
                    )
                    if (binding.switchFingerprint.isChecked) {
                        val message = getString(R.string.disable_fingerprint_message)
                        SeatelAlertDialog.with(
                            this,
                            SeatelUtils.translatForDialog(this, message)
                        )
                            .setPositiveButton(getString(R.string.yes)) { dialog, _ ->
                                dialog.dismiss()
                                binding.switchFingerprint.isChecked = false
                                FingerprintSharePreferences.getConstant(this).enableFingerprint =
                                    binding.switchFingerprint.isChecked


                            }
                            .setNegativeButton(getString(R.string.no)) { dialog, _ -> dialog.dismiss() }
                            .show()
                    } else {
                        val isFirstEnableFingerprint = FirstLoginPreference.getInstance(this)
                            ?.getFirstEnableFingerprintPreference()
                        if (isFirstEnableFingerprint!!) {
                            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                                if (hasEnrolledFingerprints()) {
                                    val text = SeatelUtils.translatForDialog(
                                        this,
                                        getString(R.string.turn_on_fingerprint)
                                    )
                                    //   showToast(text)
                                    binding.switchFingerprint.isChecked = true
                                    FingerprintSharePreferences.getConstant(this).enableFingerprint =
                                        binding.switchFingerprint.isChecked
                                } else {
                                    val message = getString(R.string.fingerprint_message)
                                    SeatelAlertDialog.with(
                                        this,
                                        SeatelUtils.translatForDialog(this, message)
                                    ).setPositiveButton(getString(R.string.yes)) { dialog, _ ->
                                        dialog.dismiss()
                                        startActivityForResult(
                                            Intent(android.provider.Settings.ACTION_SETTINGS),
                                            0
                                        )

                                    }
                                        .setNegativeButton(getString(R.string.no)) { dialog, _ -> dialog.dismiss() }
                                        .show()
                                }
                            }
                        } else {
                            startActivityForResult(
                                Intent(
                                    this,
                                    EnableFingerprintActivity::class.java
                                ), Constant.REQUEST_FINGERPRINT_CODE
                            )
                        }
                    }

                }

                "LOG_OUT" -> {
                    logout()
                    AnalyticsHelper.logEvent(
                        AnalyticsHelper.Event.SETTING_TAP_USER_LOGOUT,
                        null
                    )
                }

            }
        }
    }

    @RequiresApi(Build.VERSION_CODES.M)
    private fun hasEnrolledFingerprints(): Boolean {
        val fingerprintManager = getSystemService(FingerprintManager::class.java)
        return fingerprintManager.hasEnrolledFingerprints()
    }

    @RequiresApi(Build.VERSION_CODES.M)
    private fun hasHardwareDetected(): Boolean {
        val fingerprintManager = getSystemService(FingerprintManager::class.java)
        return fingerprintManager.isHardwareDetected
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == Constant.REQUEST_CHANGE_LANGUAGE_CODE) {
            if (resultCode == Activity.RESULT_OK) {
                val language =
                    data?.getStringExtra(Constant.LANGUAGE_CHOOSEN_DATA)
                if (language != null) {
                    updatedLogoLanguage(language)
                }
            }
        }

        if (requestCode == Constant.REQUEST_FINGERPRINT_CODE)
            if (resultCode == Activity.RESULT_OK) {
                binding.switchFingerprint.isChecked =
                    data != null && data.getStringExtra(Constant.FINGERPRINT_RESULT)
                        .equals("true")
                FingerprintSharePreferences.getConstant(this).enableFingerprint =
                    binding.switchFingerprint.isChecked
                FirstLoginPreference.getInstance(this)?.setFirstEnableFingerprintPreference(true)
                val text =
                    SeatelUtils.translatForDialog(
                        this,
                        getString(R.string.turn_on_fingerprint)
                    )
                showToast(text)
            }
    }

    private fun updatedLogoLanguage(languag: String) {
        val res = resources
        val mDrawableName = "img_" + languag.lowercase(Locale.getDefault()) + "_flag_setting"
        val resID = res.getIdentifier(mDrawableName, "drawable", this.packageName)
        Log.d("TAG:>>>", "updatedLogoLanguage: $resID $mDrawableName")
        binding.imgLanguage.setImageResource(resID)
    }

    override fun getViewBinding(): ActivitySettingBinding {
        return ActivitySettingBinding.inflate(layoutInflater)
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        activityEnterRightAnimation()
        setContentView(R.layout.activity_setting)


        //   if(!SeatelSharePreferences.getConstant(this).isPushNotification){
        //      onRegisterFirebasePushToken()
        //  }
        mUnRegisterPushTokenPresenter = UnRegisterPushTokenPresenter(this, this)

        binding.llClearCache.setOnClickListener(this)
        binding.llVersionAvailable.setOnClickListener(this)
        binding.llLanguage.setOnClickListener(this)
        binding.switchonoff.setOnCheckedChangeListener(this)
        binding.viewFingerprint.setOnClickListener(this)
        binding.viewLogOut.setOnClickListener(this)


        binding.switchonoff.isChecked = SeatelSharePreferences.getInstance(this)!!.getRegisterPush()

        val strLanguage = LanguageManager.getInstance(this).getLanguageCode()

        if (strLanguage != null) {
            updatedLogoLanguage(strLanguage)
        }
        val currentVersions = Devices.getAppVersionName(this).split("\\.")
        binding.tvAppVersion.text = "V ${currentVersions.joinToString()}"

        binding.tvCacheNum.text = analyseStorage(this)
        binding.tvCacheNum.text = binding.tvCacheNum.text.toString().replace(",", ".")
        if (!isLogIn()) {
//            llNotification.visibility = View.GONE
        }

        try {
            //fingerprint
            if (hasEnrolledFingerprints()) {
                binding.viewFingerprint.visibility = View.VISIBLE
                binding.switchFingerprint.isChecked =
                    FingerprintSharePreferences.getConstant(this).enableFingerprint
            } else if (!hasHardwareDetected()) {
                binding.viewFingerprint.visibility = View.GONE
            } else {
                binding.switchFingerprint.isChecked = false
                binding.viewFingerprint.visibility = View.GONE
                FingerprintSharePreferences.getConstant(this).enableFingerprint = false
            }


        } catch (e: Exception) {
            binding.viewFingerprint.visibility = View.GONE
        }

    }

    private fun getDirSize(dir: File): Long {
        var size: Long = 0
        for (file in dir.listFiles()!!) {
            if (file != null && file.isDirectory) {
                size += getDirSize(file)
            } else if (file != null && file.isFile) {
                size += file.length()
            }
        }
        return size
    }

    private fun analyseStorage(context: Context): String {
        var totalSize: Long = 0
        totalSize += getDirSize(context.cacheDir)
//        totalSize += getDirSize(context.externalCacheDir)
        return SeatelUtils.readableFileSize(totalSize)

//        val appBaseFolder = context.cacheDir //context.filesDir.parentFile
//        for (f in appBaseFolder.listFiles()!!) {
//            if (f.isDirectory && !f.name.equals("shared_prefs", ignoreCase = true)) {
//                val dirSize = browseFiles(f)
//                totalSize += dirSize
//            }
//        }
//        totalSize = Math.round((totalSize / 1048576).toFloat()).toLong()
//        return totalSize.toString()
    }

    private fun browseFiles(dir: File): Long {
        var dirSize: Long = 0
        for (f in dir.listFiles()!!) {
            dirSize += f.length()
            if (f.isDirectory) {
                dirSize += browseFiles(f)
            }
        }
        return dirSize

    }

    private fun gotoPlayStore() {
        val appPackageName = packageName
        try {
            startActivity(
                Intent(
                    Intent.ACTION_VIEW,
                    Uri.parse("market://details?id=$appPackageName")
                )
            )
        } catch (obj: android.content.ActivityNotFoundException) {
            startActivity(
                Intent(
                    Intent.ACTION_VIEW,
                    Uri.parse("https://play.google.com/store/apps/details?id=$appPackageName")
                )
            )
        }

    }

    private fun logout() {
        if (mDialogShow != null)
            mDialogShow?.dimissDialog()
        mDialogShow =
            SeatelAlertDialog.with(this, getString(R.string.message_logout)).setCancelable(true)
                .setNegativeButton(getString(R.string.no)) { dai, _ ->
                    dai.dismiss()
                }.setPositiveButton(getString(R.string.yes)) { _, _ ->
                    actionLogoutData()
                }.show()
    }


    private fun actionLogoutData() {
        AnalyticsHelper.logEvent(
            AnalyticsHelper.Event.SETTING_TAP_USER_LOGOUT,
            null
        )
        val phoneNumber = getPhoneLogin()
//        mUnRegisterPushTokenPresenter?.onUnRegisterPushToken(getPhoneLogin())
        SeatelSharePreferences.getInstance(this)?.clearAll()
        FirstLoginPreference.getInstance(this)?.setFirstLoginPreference(true)
        LoginManager.getInstance().logOut()
        //LoginActivity.lunch(this, phoneNumber)

        finish()
    }

    private fun animateProgressClearCache() {
        val progressAnimator =
            ObjectAnimator.ofInt(binding.pbAnimateClearCatche, "progress", 0, 100)
        progressAnimator.duration = 2000
        progressAnimator.addListener(object : Animator.AnimatorListener {

            override fun onAnimationStart(animation: Animator) {}

            override fun onAnimationEnd(animation: Animator) {
                binding.pbAnimateClearCatche.progress = 0
                clearApplicationData()
            }

            override fun onAnimationCancel(animation: Animator) {

            }

            override fun onAnimationRepeat(animation: Animator) {

            }
        })
        progressAnimator.interpolator = LinearInterpolator()
        progressAnimator.start()
    }

    private fun clearApplicationData() {
        val cache = cacheDir
        val appDir = File(cache.parent)
        if (appDir.exists()) {
            val children = appDir.list()
            for (s in children!!) {
                if (!s.equals("shared_prefs", ignoreCase = true)) {
                    deleteDir(File(appDir, s))
                }
            }
        }
    }

    private fun deleteDir(dir: File?): Boolean {
        if (dir != null && dir.isDirectory) {
            val children = dir.list()
            for (i in children!!.indices) {
                val success = deleteDir(File(dir, children[i]))
                if (!success) {
                    return false
                }
                if (i == children.size - 1) {
                    binding.tvCacheNum.text = analyseStorage(this@SettingActivity)
                    binding.tvCacheNum.text = binding.tvCacheNum.text.toString().replace(",", ".")
                }
            }
        }
        return dir!!.delete()
    }

//    fun deleteDir(dir: File?): Boolean {
//        if (dir != null && dir.isDirectory) {
//            val children = dir.list()
//            for (i in children!!.indices) {
//                val success = deleteDir(File(dir, children[i]))
//                if (!success) {
//                    return false
//                }
//                if (i == children.size - 1) {
//                    binding.tvCacheNum.text = analyseStorage(this@SettingActivity)
//                }
//            }
//            return dir.delete()
//        } else return if (dir != null && dir.isFile) {
//            dir.delete()
//        } else {
//            false
//        }
//    }


    override fun onBackPressed() {
        super.onBackPressed()
        activityExitLeftAnimation()
    }

    override fun getToolbarTitle(): String {
        return getString(R.string.setting)
    }

    companion object {
        fun lunch(context: Context) {
            val intent = Intent(context, SettingActivity::class.java)
            context.startActivity(intent)
        }
    }

    override fun onResume() {
        super.onResume()
        Handler().postDelayed({ onUpdatedScreenLanguage() }, 300)
    }

    private fun onUpdatedScreenLanguage() {
        binding.ctvLanguage.text = getString(R.string.language)
        binding.ctvNotification.text = getString(R.string.notification)
        binding.ctvClearCache.text = getString(R.string.clear_cache)
        binding.tvAppVersion.text = getString(R.string.app_version)
        //  text_view_titleBar.text = getString(R.string.setting)
        binding.ctvFingerprint.text = getString(R.string.enable_fingerprint)
        binding.ivlogout.text = getString(R.string.log_out)

    }

}
