package net.pokeranalytics.android.ui.fragment.components.bottomsheet

import android.os.Bundle
import android.text.InputType
import android.view.LayoutInflater
import android.view.View
import android.view.inputmethod.EditorInfo
import androidx.core.widget.addTextChangedListener
import kotlinx.android.synthetic.main.bottom_sheet_double_edit_text.*
import kotlinx.android.synthetic.main.fragment_bottom_sheet.view.*
import net.pokeranalytics.android.R
import net.pokeranalytics.android.exceptions.RowRepresentableEditDescriptorException
import net.pokeranalytics.android.ui.view.rowrepresentable.SessionRow
import net.pokeranalytics.android.util.extensions.round


class BottomSheetDoubleEditTextFragment : BottomSheetFragment() {

	private val values = ArrayList<String>()
	private var isEditingBlinds: Boolean = false

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

	override fun onStart() {
		super.onStart()
		if (isEditingBlinds) {
			editText2.requestFocus()
		} else {
			editText1.requestFocus()
		}
	}

	override fun getValue(): Any? {
		return values
	}

	/**
	 * Init data
	 */
	private fun initData() {
		isEditingBlinds = row == SessionRow.BLINDS
	}

	/**
	 * Init UI
	 */
	private fun initUI() {
		val data = getData()?:throw RowRepresentableEditDescriptorException("RowRepresentableEditDescriptor not found")
		if (data.size != 2) {
			throw RowRepresentableEditDescriptorException("RowRepresentableEditDescriptor inconsistency")
		}

		values.add(0, "")
		values.add(1, "")

		LayoutInflater.from(requireContext())
			.inflate(R.layout.bottom_sheet_double_edit_text, view?.bottomSheetContainer, true)

		values[0] = (data[0].defaultValue ?: "").toString()
		values[1] = (data[1].defaultValue ?: "").toString()

		data[0].hint?.let { editText1.hint = getString(it) }
		editText1.inputType = data[0].inputType ?: InputType.TYPE_CLASS_TEXT or InputType.TYPE_TEXT_FLAG_CAP_SENTENCES
		data[1].hint?.let { editText2.hint = getString(it) }
		editText2.inputType = data[1].inputType ?: InputType.TYPE_CLASS_TEXT or InputType.TYPE_TEXT_FLAG_CAP_SENTENCES

		if (valueHasPlaceholder) {
			editText1.hint = values[0]
			editText2.hint = values[1]
		} else {
			editText1.setText(values[0])
			editText2.setText(values[1])
		}

		editText1.addTextChangedListener {
			values[0] = it?.toString() ?: ""
		}

		editText2.addTextChangedListener {
			values[1] = it?.toString() ?: ""
			if (isEditingBlinds) {
				try {
					val bigBlind = values[1].toDouble()
					editText1.setText((bigBlind / 2.0).round())
				} catch (e: Exception) {
					editText1.setText("")
				}
			}
		}


		editText2.setOnEditorActionListener { _, actionId, _ ->
			if (actionId == EditorInfo.IME_ACTION_DONE) {
				this.delegate.onRowValueChanged(values, row)
				dismiss()
				true
			} else {
				false
			}
		}
	}

}