package com.seatel.mobilehall.ui.home.fragment

import android.app.Activity
import android.content.Context
import android.text.Editable
import android.text.TextUtils
import android.text.TextWatcher
import android.view.MotionEvent
import android.view.View
import android.view.ViewTreeObserver
import android.view.inputmethod.InputMethodManager
import android.widget.EditText
import androidx.recyclerview.widget.RecyclerView
import com.seatel.mobilehall.R
import com.seatel.mobilehall.ui.home.interactor.BuyYesSimCardInteractor
import com.seatel.mobilehall.util.AnimationUtil
import com.seatel.mobilehall.util.SeatelAlertDialog
import com.seatel.mobilehall.util.SeatelUtils
import com.seatel.mobilehall.util.manager.OrderingManager
import com.google.android.material.bottomsheet.BottomSheetBehavior
import kotlinx.android.synthetic.main.fragment_full_number.*
import kotlinx.android.synthetic.main.item_buy_yes_number.*


class FullNumberFragment : BaseBuySimFragment(), BuyYesSimCardInteractor.View {

    private var isClaimFreeSim: Boolean = false
    private var isWinPromotionFreeSim: Boolean = false
    private var simCardPriceFilter: Int = 0
    private val onTextChange = object : TextWatcher {
        override fun afterTextChanged(s: Editable?) {
            if (TextUtils.isEmpty(full_name_search.text.toString())) {
                buyYesSimCardPresenter?.cancelSearchPhoneNumber()
                clearDataNotify()
            }
        }

        override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {

        }

        override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {

        }

    }

    fun setIsWinPromotionFreeSim(winPromotion: Boolean) {
        this.isWinPromotionFreeSim = winPromotion
    }

    fun setClaimFreeSim(claimFree: Boolean) {
        this.isClaimFreeSim = claimFree
    }

    fun setSimCardPriceFilter(filter: Int) {
        this.simCardPriceFilter = filter
    }

    override fun getIsWinPromotionFreeSim(): Boolean {
        return isWinPromotionFreeSim
    }

    override fun onAttach(context: Context) {
        super.onAttach(context)
        setmContext(context)
        setFragmentLayout(R.layout.fragment_full_number)
        SeatelUtils.hideKeyboard((getmContext() as Activity?)!!)
    }

    override fun initRecyclerView(): RecyclerView {
        return recycler_view_full_number
    }


    private fun setKeyBoardData() {
        full_name_search.showSoftInputOnFocus = false
        keyboard_view_full_number.setmMaxLenght(10)
        keyboard_view_full_number.setmEditText(full_name_search)
    }

    //Hide Native Key Board
    fun hideKeyboard(activity: Activity) {
        // Check if no view has focus:
        val view = activity.currentFocus
        if (view != null) {
            val inputManager =
                activity.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
            inputManager.hideSoftInputFromWindow(
                view.windowToken,
                InputMethodManager.HIDE_NOT_ALWAYS
            )
        }
    }

    override fun getClaimFreeSim(): Boolean {
        return isClaimFreeSim
    }


    override fun init() {
        super.init()
        full_name_search.hint = full_name_search.hint
        if (OrderingManager.getInstance().simPriceDefault == 0.0 || isClaimFreeSim || isWinPromotionFreeSim)
            note.visibility = View.GONE
        if (isClaimFreeSim || isWinPromotionFreeSim) {
            startPrice = simCardPriceFilter
            endPrice = simCardPriceFilter
            layout_show_all.visibility = View.INVISIBLE
        }
        setKeyBoardData()
    }

    override fun initEvent() {
        super.initEvent()
        full_name_search.viewTreeObserver.addOnGlobalLayoutListener(
            object : ViewTreeObserver.OnGlobalLayoutListener {
                override fun onGlobalLayout() {
                    full_name_search.requestFocus()
                    full_name_search.viewTreeObserver.removeOnGlobalLayoutListener(this)
                }
            })

        full_name_search.setOnTouchListener { v: View, m: MotionEvent ->
            if (m.action == MotionEvent.ACTION_DOWN) {
                onEditTextSearchTouch(v)
            }
            false
        }
        button_search.setOnClickListener {
            onButtonSearchClick()
        }

        full_name_search.addTextChangedListener(onTextChange)

        view_fragment.setOnClickListener {
            AnimationUtil.instance?.collapse(layout_keyboard)
            updateUiAfterItemSelected()
        }
    }

    private fun onEditTextSearchTouch(v: View) {
        keyboard_view_full_number.setmMaxLenght(10)
        keyboard_view_full_number.showKeyBoard(v as EditText)
        full_name_search.requestFocus()
        AnimationUtil.instance?.expand(layout_keyboard)
        bottomSheetBehavior?.isHideable = true
        bottomSheetBehavior?.state = BottomSheetBehavior.STATE_HIDDEN
    }

    private fun onButtonSearchClick() {
        val search = full_name_search.text
        var msg = ""
        when {
            search!!.isEmpty() || SeatelUtils.isInvalidPhoneFormatSeatelSim(search.toString()) -> msg =
                getString(R.string.please_enter_full_number)
        }
        if (!TextUtils.isEmpty(msg)) {
            SeatelAlertDialog.with(requireContext(), msg).setCancelable(true).show()
            hideKeyBoard()
        } else {
            clearDataNotify()
            searchPhoneNumber()
        }
    }

    override fun updateUiAfterItemSelected() {
        super.updateUiAfterItemSelected()
        if (lastSelectModel != null) {
            AnimationUtil.instance?.collapse(layout_keyboard)
        }
    }

    override fun isKeyboardHided(): Boolean {
        return layout_keyboard.visibility != View.VISIBLE
    }

    override fun hideKeyBoard() {
        AnimationUtil.instance?.collapse(layout_keyboard)
    }


//    override fun onScrollUp() {
//        super.onScrollUp()
//        if (mLayoutManager?.childCount!! > 0 && isAllLoadedItem) {
//            AnimationUtil.getInstance().collapse(layout_full_number_header)
//        }
//    }

    //
//    override fun onScrollDown() {
//        super.onScrollDown()
//        if (isAllLoadedItem)
//            AnimationUtil.getInstance().expand(layout_full_number_header)
//    }


    //    override fun onScrolling() {
//        super.onScrolling()
//    }
//
//    override fun onStopScroll() {
//        super.onStopScroll()
//        if (layout_full_number_header.visibility != View.VISIBLE)
//            AnimationUtil.getInstance().expand(layout_full_number_header)
//    }
}
