package app.furmeet.events.system.schedule.abstractDataTypes.managed

import app.furmeet.events.system.helper.UncomplicatedObservable
import app.furmeet.events.system.helper.observables.Observable
import app.furmeet.events.system.helper.observables.Observer
import app.furmeet.events.system.schedule.abstractDataTypes.convention.Convention
import java.io.Serializable

class AttendeeConsFavorites : UncomplicatedObservable<Any?>(), Serializable, Observer<Any?> {
    override fun update(observable: Observable<Any?>, args: Any?) = notifyObservers(args)
    private var conventions: MutableMap<String, AttendeeConFavorites> = mutableMapOf()

    operator fun get(convention: Convention): AttendeeConFavorites {
        if (convention.id !in conventions.keys) put(AttendeeConFavorites(convention))
        if (conventions[convention.id] == null) put(AttendeeConFavorites(convention))
        return conventions[convention.id]!!
    }

    fun put(attendeeConFavorites: AttendeeConFavorites) {
        conventions[attendeeConFavorites.conventionId] = attendeeConFavorites
        attendeeConFavorites.addObserver(this)
        notifyObservers()
    }

    fun putAll(that: AttendeeConsFavorites) = this.conventions.putAll(that.conventions.apply {
        forEach { it.value.addObserver(this@AttendeeConsFavorites) }
    }).apply { notifyObservers() }

    fun clear() = conventions.apply {
        forEach { it.value.deleteObserver(this@AttendeeConsFavorites) }
    }.clear().apply { notifyObservers() }

    fun observeAllChildren() {
        conventions.values.forEach {
            it.addObserver(this)
            it.observeAllChildren()
        }
    }

    fun recursivelyRemoveObservers() {
        deleteObservers()
        conventions.values.forEach {
            it.deleteObservers()
            it.recursivelyRemoveObservers()
        }
    }
}