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


import android.annotation.SuppressLint
import android.app.Activity
import android.content.Context
import android.graphics.Point
import android.text.TextUtils
import android.view.MotionEvent
import android.view.View
import android.view.inputmethod.InputMethodManager
import android.widget.EditText
import androidx.constraintlayout.widget.ConstraintSet
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.customview.CustomEditText
import com.seatel.mobilehall.util.interactor.KeyBoardNumberInteractor
import com.seatel.mobilehall.util.manager.OrderingManager
import kotlinx.android.synthetic.main.fragment_last_four_digit.*
import kotlinx.android.synthetic.main.item_buy_yes_number.*
import kotlinx.android.synthetic.main.layout_next.*


class LastFourDigitFragment : BaseBuySimFragment(), KeyBoardNumberInteractor, View.OnClickListener,
    BuyYesSimCardInteractor.View {

    private val mEditTexts = ArrayList<CustomEditText>()
    private lateinit var mSelectEditText: EditText
    private var isClaimFreeSim: Boolean = false
    private var isWinPromotionFreeSim: Boolean = false
    private var simCardPriceFilter: Int = 0

    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 getClaimFreeSim(): Boolean {
        return isClaimFreeSim
    }

    override fun initRecyclerView(): RecyclerView {
        return recycler_view_last_digit
    }

    override fun onAttach(context: Context) {
        super.onAttach(context)
        setmContext(context)
        setFragmentLayout(R.layout.fragment_last_four_digit)
    }

    override fun init() {
        super.init()
        keyboard_view_last.setKeyBoardNumberInteractor(this)
        hideKeyboard(requireActivity())
        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
        }
        keyboard_view_last.showKeyBoard()
        mEditTexts.add(edit_text_one)
        mEditTexts.add(edit_text_two)
        mEditTexts.add(edit_text_three)
        mEditTexts.add(edit_text_four)
        for (editText in mEditTexts) editText.setOnTouchListener { _, _ -> false }

        mEditTexts[0].requestFocus()
        mSelectEditText = mEditTexts[0]
//        mHiddenTextView = text_view_hidden
        //set size on screen in when small screen size

        val display = requireActivity().windowManager.defaultDisplay
        val size = Point()
        display.getSize(size)
        val width = size.x
        val height = size.y

        if (width == 480 && height == 800) {
            val constraintSet = ConstraintSet()
            constraintSet.clone(constrain_parent)
            constraintSet.setDimensionRatio(edit_text_one.id, "0.8")
            constraintSet.setDimensionRatio(edit_text_two.id, "0.8")
            constraintSet.setDimensionRatio(edit_text_three.id, "0.8")
            constraintSet.setDimensionRatio(edit_text_four.id, "0.8")
//            constraintSet.constrainHeight(edit_text_one.id, 30)
//            constraintSet.constrainHeight(edit_text_two.id, 30)
//            constraintSet.constrainHeight(edit_text_three.id, 30)
//            constraintSet.constrainHeight(edit_text_four.id, 30)
            constraintSet.applyTo(constrain_parent)
        }


    }

    //No bottom sheet to show
    override fun initNextBottomSheet() {
    }

    override fun initEvent() {
        super.initEvent()
        button_search.setOnClickListener(this)
        layout_last_four_digits.setOnClickListener {
            AnimationUtil.instance?.collapse(keyboard_view_last)
        }
        onEditTextClick()
    }

    override fun onClick(v: View?) {
        val ediTextOne = edit_text_one.text
        val editTextTwo = edit_text_two.text
        val editTextThree = edit_text_three.text
        val editTextFour = edit_text_four.text
        var msg = ""
        when {
            ediTextOne!!.isEmpty() -> msg = getString(R.string.phone_empty)
            editTextTwo!!.isEmpty() -> msg = getString(R.string.phone_empty)
            editTextThree!!.isEmpty() -> msg = getString(R.string.phone_empty)
            editTextFour!!.isEmpty() -> msg = getString(R.string.phone_empty)
        }
        if (!TextUtils.isEmpty(msg)) {
            SeatelAlertDialog.with(requireActivity(), msg).show()
            hideKeyBoard()
        } else {
            AnimationUtil.instance?.collapse(keyboard_view_last)
            lastSelectModel = null
            updateUiAfterItemSelected()
            clearDataNotify()
            searchPhoneNumber()
        }
    }

    private fun onEditTextClick() {
        for (edit in mEditTexts) {
            edit.showSoftInputOnFocus = false
            edit.setOnTouchListener { _, event ->
                if (event.action == MotionEvent.ACTION_DOWN) {
                    mSelectEditText = edit
                    edit.setSelection(edit.text!!.length)
                    edit.requestFocus()
                    edit.isCursorVisible = true
                    AnimationUtil.instance?.expand(keyboard_view_last)
                }
                false
            }
        }
    }

    override fun searchPhoneNumber() {
        val search =
            edit_text_one.text.toString() + edit_text_two.text.toString() + edit_text_three.text.toString() + edit_text_four.text.toString()
        buyYesSimCardPresenter?.onSearchPhoneNumber(
            requireContext(),
            search,
            true,
            startPrice,
            endPrice,
            limit(),
            offset
        )
    }

    override fun onKeyBoardKeyClick(key: String) {
        onInsert(key)
    }

    override fun onKeyBoardKeyClearClick() {
        onClear()
    }

    override fun updateUiAfterItemSelected() {
        if (lastSelectModel != null) {
            AnimationUtil.instance?.collapse(keyboard_view_last)
            AnimationUtil.instance?.expand(layout_button_next)
//            layout_button_next.visibility = View.VISIBLE
        } else {
            AnimationUtil.instance?.collapse(layout_button_next)
//            layout_button_next.visibility = View.GONE
        }
    }

    private fun onInsert(key: String) {
//        if (mHiddenTextView!!.text.length == mEditTexts.size) {
//            return
//        }
//        val pos = getInsertPos(key)
//        val textView = mEditTexts[pos]
//        textView.setText(key)
//        textView.isCursorVisible = false
//        if (pos == mEditTexts.size - 1) {
//            mSelectEditText = mEditTexts[pos]
//            mEditTexts[pos].isCursorVisible = true
//            mEditTexts[pos].requestFocus()
//            return
//        }
//        mSelectEditText = mEditTexts[pos + 1]
//        mEditTexts[pos + 1].requestFocus()
        mSelectEditText.setText(key)
        mSelectEditText.isCursorVisible = false
        mSelectEditText = if (mEditTexts.indexOf(mSelectEditText) == mEditTexts.size - 1) {
            mEditTexts[mEditTexts.size - 1]
        } else {
            mEditTexts[mEditTexts.indexOf(mSelectEditText) + 1]
        }
        mSelectEditText.isCursorVisible = true
        mSelectEditText.setSelection(mSelectEditText.text.length)
        mSelectEditText.requestFocus()
    }

    private fun onClear() {
//        if (mHiddenTextView!!.text.isEmpty()) {
//            mSelectEditText = mEditTexts[0]
//            return
//        }
//        val pos = if (mSelectEditText != null) mEditTexts.indexOf(mSelectEditText) else {
//            getClearPos()
//        }
//        mEditTexts[pos].requestFocus()
//        mEditTexts[pos].isCursorVisible = true
//        mEditTexts[pos].setText("")
//        mSelectEditText = mEditTexts[pos]
        if (mSelectEditText.text.isEmpty()) {
            mSelectEditText.clearFocus()
            mSelectEditText = if (mEditTexts.indexOf(mSelectEditText) == 0) {
                mEditTexts[0]
            } else {
                mEditTexts[mEditTexts.indexOf(mSelectEditText) - 1]
            }
        }
        mSelectEditText.setText("")
        mSelectEditText.isCursorVisible = true
        mSelectEditText.setSelection(mSelectEditText.text.length)
        mSelectEditText.requestFocus()
//        val pos = getClearPos()
//        mEditTexts[pos].requestFocus()
//        mEditTexts[pos].isCursorVisible = true
//        mEditTexts[pos].setText("")
//        mHiddenTextView!!.text = null
//        for (editText in mEditTexts) {
//            editText.text = null
//        }
//        edit_text_one.requestFocus()
//        edit_text_one.isCursorVisible = true
    }


//    @SuppressLint("SetTextI18n")
//    private fun getInsertPos(key: String): Int {
//        mHiddenTextView!!.text = mHiddenTextView!!.text.toString() + key
//        return mHiddenTextView!!.text.length - 1
//    }
//
//    private fun getClearPos(): Int {
//        mHiddenTextView!!.text = mHiddenTextView!!.text.subSequence(0, mHiddenTextView!!.length() - 1)
//        return mHiddenTextView!!.text.length
//    }


    @SuppressLint("ServiceCast")
    private 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 getFragmentOffset(): Int {
        return 100
    }

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

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

}
