package com.seatel.mobilehall.ui.login.fragment

import android.content.Context
import android.hardware.fingerprint.FingerprintManager
import android.os.Build
import android.os.Bundle
import android.text.TextUtils
import android.view.LayoutInflater
import android.view.MotionEvent
import android.view.View
import android.view.ViewGroup
import android.widget.EditText
import com.android.volley.Request
import com.android.volley.VolleyError
import com.facebook.login.LoginManager
import com.google.gson.Gson
import com.seatel.mobilehall.R
import com.seatel.mobilehall.data.network.SeatelJSONObjectRequest
import com.seatel.mobilehall.data.network.SeatelSuperRequest
import com.seatel.mobilehall.data.prefs.SeatelSharePreferences
import com.seatel.mobilehall.databinding.FragmentLoginBinding
import com.seatel.mobilehall.ui.login.activity.LoginActivity
import com.seatel.mobilehall.ui.login.interactor.FingerprintInteractor
import com.seatel.mobilehall.ui.login.interactor.LoginInteractor
import com.seatel.mobilehall.ui.login.model.ProfileModel
import com.seatel.mobilehall.ui.login.prefs.FingerprintSharePreferences
import com.seatel.mobilehall.ui.login.presenter.FingerprintPresenter
import com.seatel.mobilehall.ui.login.presenter.LoginPresenter
import com.seatel.mobilehall.util.PermissionUtil
import com.seatel.mobilehall.util.SeatelAlertDialog
import com.seatel.mobilehall.util.SeatelUtils
import com.seatel.mobilehall.util.customview.ErrorHandleView
import com.seatel.mobilehall.util.viewFragmentBinding
import org.json.JSONObject

class LoginFragment : MainFragment(), FingerprintInteractor.View, LoginInteractor.View {

    private val binding by viewFragmentBinding(FragmentLoginBinding::inflate)

    private lateinit var fingerprintPresenter: FingerprintPresenter
    private var mLoginPresenter: LoginPresenter? = null
    private var isUseFingerprint: Boolean = false
    private var useFingerprintPreference = false
    private var userId = ""
    private var mPhoneNumberRequest: PermissionUtil.PermissionRequestObject? = null

    override fun onAttach(context: Context) {
        super.onAttach(context)
        setmContext(context)
        setActivity(context as LoginActivity)
        // setFragmentLayout(R.layout.fragment_login)
    }

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        return binding.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        init()
    }


    private fun init() {

        fingerprintPresenter = FingerprintPresenter(

            requireContext(), "login", binding.imgLogoFingerprint, SeatelUtils.translatForDialog(
                context,
                getString(R.string.fingerprint_not_recognized)
            ),
            this
        )
        useFingerprintPreference =
            FingerprintSharePreferences.getConstant(context).enableFingerprint
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (useFingerprintPreference && hasEnrolledFingerprints())
                fingerprintPresenter.startListenFingerprint()
            else {
                onHideLogoFingerprint()
            }
        } else onHideLogoFingerprint()

        mLoginPresenter = LoginPresenter(requireContext(), this)
        SeatelSharePreferences.getInstance(requireContext())?.setShowClaimFreeSim(true)
        // binding.imageViewBack.visibility = View.INVISIBLE

        binding.imageViewBack.setOnClickListener {
            SeatelUtils.hideKeyboard(getMainActivity())
            getMainActivity().finish()
        }


        binding.editTextPassword.hint = binding.editTextPassword.hint

        binding.editTextPhoneNumber.hint = binding.editTextPhoneNumber.hint
        binding.editTextPhoneNumber.showSoftInputOnFocus = false

        binding.keyboardView.setmMaxLenght(15)
        binding.editTextPhoneNumber.setOnTouchListener { v: View, m: MotionEvent ->
            if (m.action == MotionEvent.ACTION_DOWN) {
                SeatelUtils.hideKeyboard(getMainActivity())
                binding.editTextPhoneNumber.requestFocus()
                binding.keyboardView.showKeyBoard(v as EditText)
            }
            false
        }
        binding.editTextPassword.setOnTouchListener { _: View, m: MotionEvent ->
            if (m.action == MotionEvent.ACTION_DOWN) hideKeyBoard()

            false
        }


        binding.buttonLogin.text = getString(R.string.yes)
        binding.buttonLogin.setOnClickListener {
            validate()
            SeatelUtils.hideKeyboard(getMainActivity())
            binding.keyboardView.hideKeyBoard()
        }


        binding.textViewRegister.setOnClickListener {
            getmMainFragmentPresenter()!!.addFragment(
                SignUpFragment(),
                true
            )
        }

        binding.textViewForgetPassword.setOnClickListener {
            SeatelUtils.hideKeyboard(getMainActivity())
            getmMainFragmentPresenter()!!.addFragment(ForgotPasswordFragment(), true)
        }

        binding.linearLayoutLoginParent.setOnClickListener {
            SeatelUtils.hideKeyboard(getMainActivity())
            hideKeyBoard()
        }


    }

    private fun validate() {

        val phoneNum = binding.editTextPhoneNumber.text!!.trim()
        val pass = binding.editTextPassword.text!!.trim()

        binding.textViewLoginError.text = getString(R.string.password_empty)
        val passwordEmpty = binding.textViewLoginError.text

        binding.textViewLoginError.text = getString(R.string.pass_phone_empty)
        val passPhoneEmpty = binding.textViewLoginError.text

        var msg = ""

        if (phoneNum.isEmpty() && binding.editTextPassword.text!!.isEmpty()) {
            msg = passPhoneEmpty.toString()

        } else if (phoneNum.startsWith("0") && phoneNum.length < 9 ||
            phoneNum.startsWith("85") && phoneNum.length < 11 || phoneNum.length < 8
        ) {
            msg = getString(R.string.incorrect_phone_num)

        } else if (phoneNum.isEmpty()) {
            msg = getString(R.string.phone_empty)

        } else if (pass.isEmpty()) {
            msg = passwordEmpty.toString()
        }

        if (!TextUtils.isEmpty(msg)) {
            SeatelAlertDialog.with(requireContext(), msg).show()
            return
        }


        binding.errorView.setViewMode(ErrorHandleView.Mode.LOADING)
        mLoginPresenter?.onLogin(
            binding.editTextPhoneNumber.text.toString().trim(),
            binding.editTextPassword.text.toString().trim()
        )
    }

    private fun hasEnrolledFingerprints(): Boolean {
        val fingerprintManager = requireContext().getSystemService(FingerprintManager::class.java)
        return fingerprintManager.hasEnrolledFingerprints()
    }

    override fun onSuccessAuthenticated() {
        val phoneNumber: String = FingerprintSharePreferences.getConstant(context).phoneLogin
        if (!TextUtils.isEmpty(phoneNumber)) {
            // getMainActivity().showProgress()
            val phoneLogin: String =
                FingerprintSharePreferences.getConstant(context).phoneLogin
            val passwordLogin: String =
                FingerprintSharePreferences.getConstant(context).passwordLogin
            if (!TextUtils.isEmpty(phoneLogin) && !TextUtils.isEmpty(passwordLogin))
                mLoginPresenter?.onLogin(phoneLogin, passwordLogin)
            isUseFingerprint = true
        } else {
            onHideLogoFingerprint()
            fingerprintPresenter.stopListenFingerprint()

        }
    }

    override fun onErrorAuthenticated() {
        FingerprintSharePreferences.getConstant(context).enableFingerprint = false
        onHideLogoFingerprint()
        fingerprintPresenter.stopListenFingerprint()
        val message =
            SeatelUtils.translatForDialog(context, getString(R.string.many_attempt_message))
        showToast(message)
    }

    override fun onHideLogoFingerprint() {
        if (binding.imgLogoFingerprint.animation != null) {
            binding.imgLogoFingerprint.animation.cancel()
            binding.imgLogoFingerprint.clearAnimation()
        }

        binding.imgLogoFingerprint.visibility = View.GONE
    }

    override fun onShowLogoFingerprint() {
        binding.imgLogoFingerprint.visibility = View.VISIBLE
    }

    override fun onLoginSucceed(isNoneSeatel: Boolean, isPostPad: Boolean) {

        if (binding.editTextPhoneNumber == null) return

        if (isUseFingerprint) {

            SeatelSharePreferences.getInstance(requireContext())!!
                .setPhoneLogin(FingerprintSharePreferences.getConstant(context).phoneLogin)
            SeatelSharePreferences.getInstance(requireContext())!!
                .setMainPhoneLogin(FingerprintSharePreferences.getConstant(context).phoneLogin)
        } else {
            FingerprintSharePreferences.getConstant(requireContext()).phoneLogin =
                binding.editTextPhoneNumber.text.toString().trim()
            FingerprintSharePreferences.getConstant(requireContext()).passwordLogin =
                binding.editTextPassword.text.toString().trim()
            SeatelSharePreferences.getInstance(requireContext())!!
                .setPhoneLogin(binding.editTextPhoneNumber.text.toString().trim())
            SeatelSharePreferences.getInstance(requireContext())!!.setMainPhoneLogin(
                binding.editTextPhoneNumber.text.toString().trim()
            )
        }

        SeatelUtils.hideKeyboard(context as LoginActivity)
        SeatelSharePreferences.getInstance(requireContext())!!.setLoginSuccess("true")
        SeatelSharePreferences.getInstance(requireContext())?.setNoneSeatelNumber(isNoneSeatel)

        if (!isNoneSeatel)
            SeatelSharePreferences.getInstance(requireContext())?.setIsPostPaid(isPostPad)


        object : SeatelJSONObjectRequest(context) {

            override fun getFunctionName(): String {
                return "seatel/profile"
            }

            override fun onGetUrlParams(requestParams: RequestParams?) {
                requestParams?.put(
                    "phoneNumber",
                    SeatelSharePreferences.getInstance(requireContext())!!.getPhoneLogin()
                )
                super.onGetUrlParams(requestParams)
            }

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


        }.setOnErrorListener {
            binding.keyboardView.hideKeyBoard()
            SeatelUtils.gotoMainScreen(context)

            //getMainActivity().closeHome()
            getMainActivity().finish()
        }.execute {
            val response = it as JSONObject
            val profileModel = ProfileModel()
            profileModel.certType = response.optString("certType")
            profileModel.certNumber = response.optString("certNumber")
            profileModel.custName = response.optString("custName")
            profileModel.msisdn = response.optString("mSISDN")
            profileModel.email = response.optString("email")
            profileModel.imageUrl = response.optString("profilePicture")
            profileModel.isSnowfall = response.optBoolean("snowfall", false)
            SeatelSharePreferences.getInstance(requireContext())
                ?.setUserInfo(Gson().toJson(profileModel))
            if (binding.keyboardView != null) {
                binding.keyboardView.hideKeyBoard()
                //  MainActivity.lunch(requireContext())
                //  SeatelUtils.gotoMainScreen(context)
                // getMainActivity().closeHome()
                onBackPress()
            }
        }
    }

    override fun onLoginFailed(error: VolleyError) {
        if (binding.errorView != null) {
            binding.errorView.visibility = View.GONE
            SeatelAlertDialog.with(requireContext(), SeatelSuperRequest.getErrorMessageFrom(error))
                .show()
            LoginManager.getInstance().logOut()
        }
    }

    override fun onLoginWithSocialSucceed(uId: String) {

    }

    override fun onLoginWithSocialFail(error: String) {

    }

    override fun onAccountExist(
        isExist: Boolean,
        phoneNum: String,
        isNoneSeatel: Boolean,
        isPostPad: Boolean
    ) {
        if (isExist) {
            SeatelSharePreferences.getInstance(requireContext())?.setPasswordLogin("")
            SeatelSharePreferences.getInstance(requireContext())?.setPhoneLogin(phoneNum)
            SeatelSharePreferences.getInstance(requireContext())?.setMainPhoneLogin(phoneNum)
            SeatelSharePreferences.getInstance(requireContext())?.setLoginSuccess("true")
            SeatelSharePreferences.getInstance(requireContext())?.setNoneSeatelNumber(isNoneSeatel)
            if (!isNoneSeatel)
                SeatelSharePreferences.getInstance(requireContext())?.setIsPostPaid(isPostPad)
            SeatelUtils.gotoMainScreen(context)
            //  getMainActivity().closeHome()
            getMainActivity().finish()
        } else {
            val signUp = SignUpFragment()
            signUp.setData(userId)
            getmMainFragmentPresenter()!!.addFragment(signUp, true)
        }
        if (binding.errorView != null)
            binding.errorView.visibility = View.GONE
    }

    override fun onDestroy() {
        super.onDestroy()
        mLoginPresenter?.onDestroy()
    }

    override fun onPause() {
        super.onPause()
        fingerprintPresenter.stopListenFingerprint()
        onHideLogoFingerprint()
    }

    override fun onBackPress() {
        getmMainFragmentPresenter()?.onFragmentBackPress()
        getMainActivity().finish()
        /* super.onBackPress()
         if (MyApplication.isFirstInstall) {
             LoginActivity().activityExitFadeOutAnimation()
             if (isKeyboardHided()) LoginActivity().onBackPressed()
             else hideKeyBoard()
         } else {
             if (isKeyboardHided()) getmMainFragmentPresenter()!!.addFragment(
                 LanguageFragment(),
                 true
             )
             else hideKeyBoard()
         }*/
    }


    override fun isKeyboardHided(): Boolean {
        return binding.keyboardView.visibility == View.GONE
    }

    override fun hideKeyBoard() {
        super.hideKeyBoard()
        if (binding.keyboardView != null)
            binding.keyboardView.hideKeyBoard()
    }

    override fun onResume() {
        super.onResume()
        if (binding.errorView != null)
            binding.errorView.visibility = View.GONE
    }

    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<out String>,
        grantResults: IntArray
    ) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        mPhoneNumberRequest?.onRequestPermissionsResult(requestCode, permissions, grantResults)
    }

    private fun setPhoneNum(phoneNum: String) {
        if (binding.editTextPhoneNumber != null) {
            binding.editTextPhoneNumber.setText(phoneNum)
            binding.editTextPhoneNumber.setSelection(phoneNum.length)
        }
    }
}
