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

import android.content.Context
import android.content.Intent
import android.hardware.fingerprint.FingerprintManager
import android.os.Build
import android.os.Bundle
import android.text.TextUtils
import android.view.MotionEvent
import android.view.View
import android.widget.EditText
import androidx.appcompat.app.AppCompatActivity
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.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 kotlinx.android.synthetic.main.fragment_login.*
import org.json.JSONObject

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


    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 onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        init()
    }


    private fun init() {

        fingerprintPresenter = FingerprintPresenter(

            requireContext(), "login", img_logo_fingerprint, 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)
        // image_view_back.visibility = View.INVISIBLE

        image_view_back.setOnClickListener {
            SeatelUtils.hideKeyboard(getMainActivity())
            getMainActivity().finish()
        }


        edit_text_password.hint = edit_text_password.hint

        edit_text_phone_number.hint = edit_text_phone_number.hint
        edit_text_phone_number.showSoftInputOnFocus = false

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

            false
        }


        button_login.text = getString(R.string.yes)
        button_login.setOnClickListener {
            validate()
            SeatelUtils.hideKeyboard(getMainActivity())
            keyboard_view.hideKeyBoard()
        }


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

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

        linear_layout_login_parent.setOnClickListener {
            SeatelUtils.hideKeyboard(getMainActivity())
            hideKeyBoard()
        }


    }

    private fun validate() {

        val phoneNum = edit_text_phone_number.text!!.trim()
        val pass = edit_text_password.text!!.trim()

        text_view_login_error.text = getString(R.string.password_empty)
        val passwordEmpty = text_view_login_error.text

        text_view_login_error.text = getString(R.string.pass_phone_empty)
        val passPhoneEmpty = text_view_login_error.text

        var msg = ""

        if (phoneNum.isEmpty() && edit_text_password.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
        }


        error_view.setViewMode(ErrorHandleView.Mode.LOADING)
        mLoginPresenter?.onLogin(
            edit_text_phone_number.text.toString().trim(),
            edit_text_password.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 (img_logo_fingerprint.animation != null) {
            img_logo_fingerprint.animation.cancel()
            img_logo_fingerprint.clearAnimation()
        }

        img_logo_fingerprint.visibility = View.GONE
    }

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

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

        if (edit_text_phone_number == 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 =
                edit_text_phone_number.text.toString().trim()
            FingerprintSharePreferences.getConstant(requireContext()).passwordLogin =
                edit_text_password.text.toString().trim()
            SeatelSharePreferences.getInstance(requireContext())!!
                .setPhoneLogin(edit_text_phone_number.text.toString().trim())
            SeatelSharePreferences.getInstance(requireContext())!!.setMainPhoneLogin(
                edit_text_phone_number.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 {
            keyboard_view.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 (keyboard_view != null) {
                keyboard_view.hideKeyBoard()
                //  MainActivity.lunch(requireContext())
                //  SeatelUtils.gotoMainScreen(context)
                // getMainActivity().closeHome()
                onBackPress()
            }
        }
    }

    override fun onLoginFailed(error: VolleyError) {
        if (error_view != null) {
            error_view.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 (error_view != null)
            error_view.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 keyboard_view.visibility == View.GONE
    }

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

    override fun onResume() {
        super.onResume()
        if (error_view != null)
            error_view.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 (edit_text_phone_number != null) {
            edit_text_phone_number.setText(phoneNum)
            edit_text_phone_number.setSelection(phoneNum.length)
        }
    }
}
