package net.pokeranalytics.android.ui.fragment

import android.content.DialogInterface
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import androidx.appcompat.app.AlertDialog
import androidx.recyclerview.widget.LinearLayoutManager
import io.realm.RealmObject
import kotlinx.android.synthetic.main.fragment_editable_data.*
import kotlinx.android.synthetic.main.fragment_editable_data.view.*
import net.pokeranalytics.android.R
import net.pokeranalytics.android.model.LiveData
import net.pokeranalytics.android.model.ObjectSavable
import net.pokeranalytics.android.ui.activity.components.PokerAnalyticsActivity
import net.pokeranalytics.android.ui.adapter.components.*
import net.pokeranalytics.android.ui.fragment.components.PokerAnalyticsFragment
import net.pokeranalytics.android.ui.fragment.components.bottomsheet.BottomSheetDelegate
import net.pokeranalytics.android.ui.fragment.components.bottomsheet.BottomSheetFragment
import net.pokeranalytics.android.ui.view.RowEditable
import net.pokeranalytics.android.ui.view.RowRepresentable
import timber.log.Timber

class EditableDataFragment : PokerAnalyticsFragment(), RowRepresentableDelegate, BottomSheetDelegate {

    private lateinit var item: RealmObject
	private lateinit var liveDataType: LiveData
	private lateinit var rowRepresentableAdapter: RowRepresentableAdapter

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

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

	override fun onRowSelected(row: RowRepresentable) {
		BottomSheetFragment.create(fragmentManager, row, this, (this.item as RowEditable).getBottomSheetData(row))
	}

	override fun clickOnAdd(row: RowRepresentable) {
		Toast.makeText(requireContext(), "Add new element: $row", Toast.LENGTH_SHORT).show()
	}

	override fun clickOnClear(row: RowRepresentable) {
		Toast.makeText(requireContext(), "Clear: $row", Toast.LENGTH_SHORT).show()
		(this.item as RowEditable).updateValue(null, row)
		this.getRealm().executeTransaction {
			it.copyToRealmOrUpdate(this.item)
		}
		rowRepresentableAdapter.refreshRow(row)
	}

	override fun setValue(value: Any?, row: RowRepresentable) {
		(this.item as RowEditable).updateValue(value, row)
		this.getRealm().executeTransaction {
			it.copyToRealmOrUpdate(this.item)
		}
		rowRepresentableAdapter.refreshRow(row)
	}

	private fun initData() {
	}

	/**
	 * Init UI
	 */
	private fun initUI() {
		val activity = activity as PokerAnalyticsActivity
		activity.setSupportActionBar(toolbar)
		activity.supportActionBar?.setDisplayHomeAsUpEnabled(true)

		val viewManager = LinearLayoutManager(requireContext())

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

		this.saveButton.text = this.saveButton.context.getString(R.string.save)
		this.saveButton.setOnClickListener {

			if ((this.item as ObjectSavable).isValidForSave()) {
				this.getRealm().executeTransaction {
					it.copyToRealmOrUpdate(this.item)
				}
				this.activity?.let {
					it.finish()
				}
			} else {
				val builder = AlertDialog.Builder(it.context)
					.setMessage(R.string.empty_name_for_br_error)
					.setNegativeButton(R.string.ok, null)
				builder.show()
			}
		}

		this.deleteButton.text = this.deleteButton.context.getString(R.string.delete)
		this.deleteButton.setOnClickListener {
			val builder = AlertDialog.Builder(it.context)
			builder.setTitle(R.string.warning)
				.setMessage(R.string.are_you_sure_you_want_to_do_that_)
				.setNeutralButton(R.string.no, null)
				.setNegativeButton(R.string.yes, DialogInterface.OnClickListener { dialog, id ->

					if (this.item.isManaged) {
						Toast.makeText(requireContext(), "isManaged", Toast.LENGTH_SHORT).show()
						Timber.d("is managed")
						this.getRealm().executeTransaction {
							this.liveDataType.deleteData(it, (this.item as LiveDataDataSource))
						}
 					} else {
						Toast.makeText(requireContext(), "isNotManaged", Toast.LENGTH_SHORT).show()
						Timber.d("is not managed")
					}
					this.activity?.let {
						it.finish()
					}
				})
			builder.show()
		}
	}

	/**
	 * Set fragment data
	 */
	fun setData(dataType: Int, primaryKey: String?) {
		this.liveDataType = LiveData.values()[dataType]
		var proxyItem : RealmObject? = this.liveDataType.getData(this.getRealm(), primaryKey)
        proxyItem?.let {
			this.appBar.toolbar.title = "Update ${this.liveDataType.name.toLowerCase().capitalize()}"
		} ?: run {
			this.appBar.toolbar.title = "New ${this.liveDataType.name.toLowerCase().capitalize()}"
		}
		this.item = this.liveDataType.updateOrCreate(this.getRealm(), primaryKey)
		this.rowRepresentableAdapter = RowRepresentableAdapter((this.item as RowRepresentableDataSource), this)
		this.recyclerView.adapter = rowRepresentableAdapter
	}
}