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_edit_text.*
import kotlinx.android.synthetic.main.fragment_bottom_sheet.view.*
import net.pokeranalytics.android.R
import net.pokeranalytics.android.exceptions.RowRepresentableEditDescriptorException
import java.text.NumberFormat


class BottomSheetNumericTextFragment : BottomSheetFragment() {

	private var value: Double? = null

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

	override fun onStart() {
		super.onStart()
		editText1.requestFocus()
	}

	override fun getValue(): Any? {
		return this.value
	}

	/**
	 * Init data
	 */
	private fun initData() {
	}

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

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

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

			this.value = try {
				editText1.text.toString().toDouble()
			} catch (e: Exception) {
				null
			}

		}
		data[0].defaultValue?.let {
			val valueString = if (it is Double || it is Long) {
				val formatter = NumberFormat.getNumberInstance()
				formatter.maximumFractionDigits = 6
				formatter.isGroupingUsed = false
				formatter.format(it)
			} else {
				it.toString()
			}

			if (valueHasPlaceholder) {
				this.value = it.toString().toDoubleOrNull()
				editText1.hint = valueString
			} else {
				editText1.setText(valueString)
			}
		}

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

}