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

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import androidx.recyclerview.widget.LinearLayoutManager
import kotlinx.android.synthetic.main.bottom_sheet_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.ui.adapter.RowRepresentableAdapter
import net.pokeranalytics.android.ui.adapter.RowRepresentableDelegate
import net.pokeranalytics.android.ui.adapter.StaticRowRepresentableDataSource
import net.pokeranalytics.android.ui.view.RowRepresentable

class BottomSheetStaticListFragment : BottomSheetFragment(), StaticRowRepresentableDataSource,
    RowRepresentableDelegate {

	private var staticRows: List<RowRepresentable> = emptyList()
	private lateinit var dataAdapter: RowRepresentableAdapter

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

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

    override fun adapterRows(): List<RowRepresentable>? {
        return this.staticRows
    }

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

	/**
	 * Init data
	 */
	private fun initData() {
		val bottomSheetData = getData()?:throw RowRepresentableEditDescriptorException("RowRepresentableEditDescriptor not found")
		if (bottomSheetData.size != 1) {
			throw RowRepresentableEditDescriptorException("RowRepresentableEditDescriptor inconsistency")
		}
		if (bottomSheetData.first().staticData == null) {
			throw RowRepresentableEditDescriptorException("RowRepresentableEditDescriptor inconsistency")
		}
		this.staticRows = bottomSheetData.first().staticData as List<RowRepresentable>
	}

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

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

		reyclerView.apply {
			setHasFixedSize(true)
			layoutManager = viewManager
			adapter = dataAdapter
		}
	}

}