<?php

namespace Ciext\Model;

abstract class AbstractEventModel extends \CI_Model implements \SplSubject
{

    protected $event_name = '';
    protected $event_data = [];
    protected $observers = [];

    /**
     * Add observer
     * @param \SplObserver $observer
     * @return $this
     */
    #[\ReturnTypeWillChange]
    public function attach(\SplObserver $observer)
    {
        $this->observers[] = $observer;
        return $this;
    }

    /**
     * Remove observer
     * @param \SplObserver $observer
     * @return $this
     */
    #[\ReturnTypeWillChange]
    public function detach(\SplObserver $observer)
    {

        $key = array_search($observer, $this->observers, true);
        if ($key !== false) {
            unset($this->observers[$key]);
        }
        return $this;
    }

    /**
     * Remove all observers
     * @return $this
     */
    public function detach_all()
    {
        $this->observers = [];
        return $this;
    }

    /**
     * Notify observers
     * @param string $event_name
     * @param mixed $event_data
     * @return $this
     */
    #[\ReturnTypeWillChange]
    public function notify($event_name = '', $event_data = [])
    {
        foreach ($this->observers as $value) {
            if (!empty($event_name)) {
                $this->event_name = $event_name;
            }
            if (!empty($event_data)) {
                $this->event_data = $event_data;
            }
            $value->update($this);
        }
        return $this;
    }

    /**
     * Get event name
     * @return string
     */
    public function get_event_name()
    {
        return $this->event_name;
    }

    /**
     * Get event data
     * @return mixed
     */
    public function get_event_data()
    {
        return $this->event_data;
    }

}
