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

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import androidx.core.view.get
import androidx.recyclerview.widget.LinearLayoutManager
import com.google.android.material.chip.Chip
import kotlinx.android.synthetic.main.bottom_sheet_game_list.*
import kotlinx.android.synthetic.main.fragment_bottom_sheet.view.*
import net.pokeranalytics.android.R
import net.pokeranalytics.android.exceptions.RowRepresentableEditDescriptorException
import net.pokeranalytics.android.model.Limit
import net.pokeranalytics.android.ui.adapter.RowRepresentableAdapter
import net.pokeranalytics.android.ui.extensions.px
import net.pokeranalytics.android.ui.view.RowRepresentable

/**
 * Bottom Sheet List Game Fragment
 * Display a list of game + chips to choose the game limit
 */
class BottomSheetListGameFragment : BottomSheetListFragment() {

	private var limit: Int? = 0
	private val values = ArrayList<Any?>()

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

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

	override fun onRowSelected(position: Int, row: RowRepresentable, fromAction: Boolean) {
		realmData?.let {
			val selectedData = it[position]
			selectedData?.let { data ->
				values[1] = data
				this.delegate.onRowValueChanged(values, this.row)
				dismiss()
			}
		}
	}

	/**
	 * Init data
	 */
	override fun initData() {
		val bottomSheetData = getData()?:throw RowRepresentableEditDescriptorException("RowRepresentableEditDescriptor not found")
		if (bottomSheetData.size != 2) {
			throw RowRepresentableEditDescriptorException("RowRepresentableEditDescriptor inconsistency")
		}
		if (bottomSheetData[1].data == null) {
			throw RowRepresentableEditDescriptorException("RowRepresentableEditDescriptor inconsistency")
		}
		this.limit = bottomSheetData[0].defaultValue as Int?
		this.realmData = bottomSheetData[1].data
	}

	/**
	 * Init UI
	 */
	override fun initUI() {
		LayoutInflater.from(requireContext()).inflate(R.layout.bottom_sheet_game_list, view?.bottomSheetContainer, true)

		values.add(0, limit)
		values.add(1, null)

		chipGroup.removeAllViews()
		Limit.values().forEach {
			val chip = Chip(requireContext())
			chip.id = it.ordinal
			chip.text = it.shortName
			chip.chipStartPadding = 8f.px
			chip.chipEndPadding = 8f.px
			chip.isChecked = it.ordinal == limit
			chipGroup.addView(chip)
		}

		chipGroup.setOnCheckedChangeListener { _, i ->
			values[0] = i
		}

		if (limit == null) {
			(chipGroup[0] as Chip).isChecked = true
		}

		val viewManager2 = LinearLayoutManager(requireContext())
		dataAdapter = RowRepresentableAdapter(this, this)

		recyclerView2.apply {
			setHasFixedSize(true)
			layoutManager = viewManager2
			adapter = dataAdapter
		}

	}

}