package net.pokeranalytics.android.model.realm

import android.content.Context
import com.google.android.libraries.places.api.model.Place
import io.realm.Realm
import io.realm.RealmObject
import io.realm.annotations.PrimaryKey
import io.realm.kotlin.where
import net.pokeranalytics.android.R
import net.pokeranalytics.android.model.interfaces.NameManageable
import net.pokeranalytics.android.model.interfaces.SaveValidityStatus
import net.pokeranalytics.android.ui.view.RowRepresentable
import net.pokeranalytics.android.ui.view.rowrepresentable.SimpleRow
import java.util.*


open class Location : RealmObject(), NameManageable, RowRepresentable {

	@PrimaryKey
	override var id = UUID.randomUUID().toString()

	// The name of the location
	override var name: String = ""

	// The readable address of the location
	private var address: String? = null

	// the longitude of the location
	var longitude: Double? = null

	// the latitude of the location
	var latitude: Double? = null

	override fun getDisplayName(context: Context): String {
		return this.name
	}

	override fun updateValue(value: Any?, row: RowRepresentable) {
		when (row) {
			SimpleRow.NAME -> this.name = value as String? ?: ""
		}
	}

	/**
	 * Fill the location attributes with a place object
	 */
	fun setPlace(place: Place) {
		this.name = place.name ?: ""
		this.address = place.address ?: ""
		this.latitude = place.latLng?.latitude
		this.longitude = place.latLng?.longitude
	}

	override fun getFailedSaveMessage(status: SaveValidityStatus): Int {
        return when (status) {
            SaveValidityStatus.DATA_INVALID -> R.string.location_empty_field_error
            SaveValidityStatus.ALREADY_EXISTS -> R.string.duplicate_location_error
            else -> super.getFailedSaveMessage(status)
        }
	}

	override fun isValidForDelete(realm: Realm): Boolean {
		return realm.where<Session>().equalTo("location.id", id).findAll().isEmpty()
	}
}
