package com.seatel.mobilehall.ui.login.activity

import android.animation.ValueAnimator
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.util.DisplayMetrics
import android.view.View
import android.view.View.SCROLL_AXIS_HORIZONTAL
import android.view.ViewTreeObserver
import com.seatel.mobilehall.R
import com.seatel.mobilehall.data.prefs.SeatelSharePreferences
import com.seatel.mobilehall.ui.application.MyApplication
import com.seatel.mobilehall.ui.base.activity.BaseActivity
import com.seatel.mobilehall.ui.login.fragment.*
import com.seatel.mobilehall.ui.login.interactor.MainInteractor
import com.seatel.mobilehall.ui.login.presenter.MainPresenter
import com.seatel.mobilehall.ui.login.presenter.UnRegisterPushTokenPresenter
import com.seatel.mobilehall.util.Constant
import com.seatel.mobilehall.util.SeatelUtils
import com.seatel.mobilehall.util.lang.FirstLoginPreference
import kotlinx.android.synthetic.main.activity_login.*


class LoginActivity : BaseActivity(), MainInteractor.View, ViewTreeObserver.OnGlobalLayoutListener {


    private var mBaseFragment: MainFragment? = null
    private var mainPresenter: MainPresenter? = null

    private var phoneNumberForUnregisterPush = ""
    private var mUnRegisterPushTokenPresenter: UnRegisterPushTokenPresenter? = null

    private val scrollSkyLineDuration: Long = 500
    private var scrollYSkyDuration: Long = 300
    private var isModifyProfile = false
    private var mTempOffset = 0
    private var isScrollUP = true
    private var running = false


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_login)
        activityEnterFadeInAnimation()
        init()

    }


    private fun init() {

        val str = FirstLoginPreference.getInstance(applicationContext)?.getFirstLoginPreference()
        if (str != null) MyApplication.isFirstInstall = str

        mainPresenter = MainPresenter(this)
        initParallaxView()

        var isAddNewPhone = false
        if (intent.hasExtra(Constant.IS_NEW_PHONE))
            isAddNewPhone = intent.getBooleanExtra(Constant.IS_NEW_PHONE, false)

        if (intent.hasExtra(Constant.IS_MODIFY_PROFILE))
            isModifyProfile = intent.getBooleanExtra(Constant.IS_MODIFY_PROFILE, false)

        val phone = intent.getStringExtra("phoneNum")
        val id = intent.getStringExtra("openId")
        val isExist = intent.getBooleanExtra("isExist", false)
        if (isExist) {
            SeatelSharePreferences.getInstance(applicationContext)?.setPasswordLogin("")
            SeatelSharePreferences.getInstance(applicationContext)?.setPhoneLogin("")
            SeatelSharePreferences.getInstance(applicationContext)?.setLoginSuccess("true")
            finish()
        } else {

            if (isAddNewPhone || isModifyProfile) {
                scrollYSkyDuration = 500
                /**
                 * ForgetPasswordFragment
                 */
                val forgotPass = ForgotPasswordFragment()
                if (isAddNewPhone)
                    forgotPass.setDataForAddNewPhone(getMainPhoneLogin())
                else forgotPass.setDataForModifyProfile(Constant.VERRIFY_PHONE_NUMBER)
                setFragment(forgotPass, true)

            } else if (phone != null && id != null) {
                /**
                 * SignUpFragment
                 */
                val signUp = SignUpFragment()
                signUp.setData(id)
                setFragment(signUp, true)
            } else {
                if (MyApplication.isFirstInstall) {
                    if (phoneNumberForUnregisterPush.isNotEmpty())
                        mUnRegisterPushTokenPresenter?.onUnRegisterPushToken(
                            phoneNumberForUnregisterPush
                        )
                    /**
                     * LoginFragment
                     */
                    setFragment(LoginFragment(), true)
                    /**
                     * LanguageFragment
                     */
                }
                //else setFragment(LanguageFragment(), false)
            }

        }
    }

    fun closeHome() {
        activityExitFadeOutAnimation()
        finish()
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        mBaseFragment?.onActivityResult(requestCode, resultCode, data)
    }

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

    override fun setFragment(fragment: MainFragment, isAnim: Boolean) {
        val delayAnimate = Handler(Looper.getMainLooper())
        delayAnimate.postDelayed({
            doAnimation(fragment, isAnim)
        }, 200)
    }

    private fun doAnimation(fragment: MainFragment, isAnim: Boolean) {
        mBaseFragment = fragment
        mainPresenter?.let { fragment.attachPresenter(it) }
        val transaction = supportFragmentManager.beginTransaction()
        if (isAnim) {
            transaction.setCustomAnimations(
                R.anim.home_fragment_fade_in,
                R.anim.home_fragment_fade_out
            )
            if (mBaseFragment is ForgotPasswordFragment) scrollBackgroundY(true)
            else if (mBaseFragment is LoginFragment && isScrollUP) scrollBackgroundY(false)
            if (mBaseFragment !is SignUpFragment && mBaseFragment !is NewPasswordFragment && mBaseFragment !is ForgotPasswordFragment) scrollBackgroundX()
        }

        if (mBaseFragment != null) {
            val baseFragment = mBaseFragment
            transaction.replace(R.id.relative_layout_home_parent, baseFragment!!)
                .addToBackStack(null)
                .show(baseFragment)
                .commit()
        }

    }

    private fun scrollBackgroundY(isScrollUp: Boolean) {
        if (isScrollUp)

            parallax_view_sky_line.viewTreeObserver.addOnGlobalLayoutListener(this)

        val displayMetrics = DisplayMetrics()
        this.windowManager.defaultDisplay.getMetrics(displayMetrics)
        val targetPos = (displayMetrics.heightPixels / 2 -
                (parallax_view_sky_line.height / 2 + SeatelUtils.convertDpToPx(
                    applicationContext,
                    10
                )))

        if (isScrollUp) translateY(-targetPos.toFloat())
        else translateY(0f)
        isScrollUP = isScrollUp
    }

    private fun translateY(targetPos: Float) {
        parallax_view_sky_line.visibility = View.VISIBLE
        parallax_view_sky_line.animate().translationY(targetPos).duration = scrollYSkyDuration
        view.animate().translationY(targetPos).duration = scrollYSkyDuration
    }

    private fun scrollBackgroundX() {
        val endOffset: Int = mBaseFragment?.getFragmentOffset()!!

        val anim: ValueAnimator = ValueAnimator.ofInt(mTempOffset, endOffset)
        anim.duration = scrollSkyLineDuration
        anim.addUpdateListener { animation ->

            val animProgress = animation.animatedValue as Int
            val offSet = animProgress.toFloat() / 100
            parallax_view_sky_line.setOffset(offSet)
        }

        anim.start()
        mTempOffset = endOffset
    }

    override fun onSmsResponse(body: String, sender: String) {
        if (!running || mBaseFragment == null) return
        if (mBaseFragment is ConfirmationForgotPassFragment) {
            (mBaseFragment as ConfirmationForgotPassFragment).smsResponse(body, sender)
        } else if (mBaseFragment is ConfirmationFragment) {
            (mBaseFragment as ConfirmationFragment).smsResponse(body, sender)
        }
    }

    override fun onGlobalLayout() {
        val displayMetrics = DisplayMetrics()
        this.windowManager.defaultDisplay.getMetrics(displayMetrics)
        val targetPos = (displayMetrics.heightPixels / 2 -
                (parallax_view_sky_line.height / 2 + SeatelUtils.convertDpToPx(
                    applicationContext,
                    10
                )))
        translateY(-targetPos.toFloat())
        parallax_view_sky_line.viewTreeObserver.removeOnGlobalLayoutListener(this)
    }

    private fun initParallaxView() {
        parallax_view_sky_line.setActualImageResource(R.drawable.sky_line_bg)
        parallax_view_sky_line.canScrollHorizontally(SCROLL_AXIS_HORIZONTAL)
        if (!MyApplication.isFirstInstall)
            parallax_view_sky_line.visibility = View.VISIBLE
    }

    override fun isDisplayToolbar(): Boolean {
        return false
    }

    override fun isStatusBarColorDark(): Boolean {
        return true
    }

    override fun onBackPressed() {
        super.onBackPressed()
        mBaseFragment?.onBackPress()
    }

    companion object {
        fun lunch(context: Context, phoneNumber: String = "") {
            val intent = Intent(context, LoginActivity::class.java)
            intent.putExtra(Constant.PHONE_NUMBER, phoneNumber)
            // intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK
            context.startActivity(intent)
        }

        fun launchWithAddNewPhone(
            context: Context,
            isNewPhoneNumber: Boolean = true,
            isModifyProfile: Boolean = false
        ) {
            val intent = Intent(context, LoginActivity::class.java)
            intent.putExtra(Constant.IS_NEW_PHONE, isNewPhoneNumber)
            intent.putExtra(Constant.IS_MODIFY_PROFILE, isModifyProfile)
            context.startActivity(intent)
        }
    }
}