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 io.realm.RealmResults
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.model.realm.Game
import net.pokeranalytics.android.ui.adapter.LimitTypesAdapter
import net.pokeranalytics.android.ui.adapter.components.LiveDataAdapter
import net.pokeranalytics.android.ui.adapter.components.LiveDataDataSource
import net.pokeranalytics.android.ui.adapter.components.LiveDataDelegate
import timber.log.Timber


class BottomSheetListGameFragment : BottomSheetFragment(), LiveDataDelegate {

	private var realmData: RealmResults<*>? = null
	private lateinit var dataAdapter: LiveDataAdapter

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

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

	override fun data(position: Int): LiveDataDataSource {
		realmData?.let {
			return it[position] as LiveDataDataSource
		}
		//TODO: Change that
		return Game()
	}

	override fun onRowSelected(position: Int) {
		realmData?.let {
			val selectedData = it[position]
			selectedData?.let {data ->
				bottomSheetDelegate.setValue(data, row)
				dismiss()
			}
		}
	}

	override fun size(): Int {

		Timber.d("Games: ${realmData?.size}")

		return realmData?.size ?: 0
	}

	/**
	 * Init data
	 */
	private fun initData() {
		val bottomSheetData = getData()
		if (bottomSheetData.isNotEmpty() && bottomSheetData.size >= 2 && bottomSheetData[1].data != null) {
			this.realmData = bottomSheetData[1].data as RealmResults<*>
		}
	}

	/**
	 * Init UI
	 */
	private fun initUI() {

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

		val limits = ArrayList<String>()
		limits.addAll(resources.getStringArray(R.array.limit_short_name))


		val viewManager1 = LinearLayoutManager(requireContext())
		val gameDataAdapter1 = LimitTypesAdapter(limits)

		recyclerView1.apply {
			setHasFixedSize(true)
			layoutManager = viewManager1
			adapter = gameDataAdapter1
			isNestedScrollingEnabled = false
		}


		val viewManager2 = LinearLayoutManager(requireContext())
		dataAdapter = LiveDataAdapter(this, R.layout.row_bottom_sheet_title)

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

	}

}