package net.pokeranalytics.android.ui.fragment

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.LinearLayoutManager
import io.realm.Realm
import io.realm.RealmResults
import kotlinx.android.synthetic.main.fragment_data_list.*
import net.pokeranalytics.android.R
import net.pokeranalytics.android.ui.activity.EditableDataActivity
import net.pokeranalytics.android.ui.adapter.components.*
import net.pokeranalytics.android.ui.fragment.components.PokerAnalyticsFragment
import net.pokeranalytics.android.ui.view.SettingRow
import timber.log.Timber

class DataListFragment : PokerAnalyticsFragment(), LiveDataDelegate {

	private lateinit var dataType: SettingRow

    private lateinit var items: RealmResults<*>

	override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
		return inflater.inflate(R.layout.fragment_data_list, container, false)
	}

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

	override fun data(position: Int): LiveDataDataSource {
        return (items[position] as LiveDataDataSource)
	}

	override fun onRowSelected(position: Int) {
		this.dataType.relatedResultsRepresentable?.let {
			EditableDataActivity.newInstance(requireContext(), it.ordinal, this.data(position).primaryKey)
		}
	}

    override fun size(): Int {
        return items.size
    }

    private fun initData() {
    }

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

		val viewManager = LinearLayoutManager(requireContext())
		val dataListAdapter = LiveDataAdapter(this)

		recyclerView.apply {
			setHasFixedSize(true)
			layoutManager = viewManager
			adapter = dataListAdapter
		}

		this.addButton.setOnClickListener {
			this.dataType.relatedResultsRepresentable?.let {
				EditableDataActivity.newInstance(
					requireContext(),
					dataType = it.ordinal,
					primaryKey = null
				)
			}
		}

	}


	/**
	 * Set fragment data
	 */
	fun setData(dataType: Int) {
		this.dataType = SettingRow.values()[dataType]
		this.title.text = this.dataType.name.toLowerCase().capitalize()
		val realm = Realm.getDefaultInstance()

		this.dataType.relatedResultsRepresentable?.let {
			this.items = it.items(realm)
			this.items.addChangeListener { newItems ->
				Timber.d("newItems: ${newItems.size}")
				this.recyclerView.adapter?.notifyDataSetChanged()
			}
		}
	}
}