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

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import androidx.recyclerview.widget.GridLayoutManager
import kotlinx.android.synthetic.main.bottom_sheet_grid.*
import kotlinx.android.synthetic.main.fragment_bottom_sheet.view.*
import net.pokeranalytics.android.exceptions.RowRepresentableEditDescriptorException
import net.pokeranalytics.android.model.TableSize
import net.pokeranalytics.android.ui.adapter.RowRepresentableAdapter
import net.pokeranalytics.android.ui.adapter.RowRepresentableDelegate
import net.pokeranalytics.android.ui.adapter.StaticRowRepresentableDataSource
import net.pokeranalytics.android.ui.view.GridSpacingItemDecoration
import net.pokeranalytics.android.ui.view.RowRepresentable
import net.pokeranalytics.android.ui.extensions.px

class BottomSheetTableSizeGridFragment : BottomSheetFragment(), StaticRowRepresentableDataSource, RowRepresentableDelegate {

	private lateinit var dataAdapter: RowRepresentableAdapter
	private var defaultSize: Int? = null

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

	override fun onResume() {
		super.onResume()
		dataAdapter.notifyDataSetChanged()
	}

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

	/**
	 * Init data
	 */
	private fun initData() {
		val bottomSheetData = getData()?:throw RowRepresentableEditDescriptorException("RowRepresentableEditDescriptor not found")
		if (bottomSheetData.size != 1) {
			throw RowRepresentableEditDescriptorException("RowRepresentableEditDescriptor inconsistency")
		}
		defaultSize = bottomSheetData.first().defaultValue as Int?
	}

	/**
	 * Init UI
	 */
	private fun initUI() {
		LayoutInflater.from(requireContext())
			.inflate(net.pokeranalytics.android.R.layout.bottom_sheet_grid, view?.bottomSheetContainer, true)

		val viewManager = GridLayoutManager(requireContext(), 3)
		dataAdapter = RowRepresentableAdapter(this, this)

		val spanCount = 3
		val spacing = 2.px
		val includeEdge = false

		reyclerView.apply {
			setHasFixedSize(true)
			layoutManager = viewManager
			adapter = dataAdapter
			addItemDecoration(GridSpacingItemDecoration(spanCount, spacing, includeEdge))
		}
	}

	override fun adapterRows(): List<RowRepresentable>? {
		return TableSize.all
	}

	override fun onRowSelected(position: Int, row: RowRepresentable, fromAction: Boolean) {
		this.delegate.onRowValueChanged((row as TableSize).numberOfPlayer, this.row)
		dismiss()
	}

	override fun stringForRow(row: RowRepresentable): String {
		this.context?.let {
			return row.localizedTitle(it)
		}
		return "UNKNOWN CONTEXT FOR ROW $row"
	}
}