<?php
namespace boru\ai\Conversation;

class ConversationMemory
{
    /** @var string|null */
    protected $title;

    /** @var string|null */
    protected $summary;

    /** @var ConversationNote[] */
    protected $notes = array();

    /** @var array */
    protected $metadata = array();

    public function title($value = null)
    {
        if ($value !== null) {
            $this->title = (string)$value;
            return $this;
        }
        return $this->title;
    }

    public function summary($value = null)
    {
        if ($value !== null) {
            $this->summary = (string)$value;
            return $this;
        }
        return $this->summary;
    }

    public function addNote(ConversationNote $note)
    {
        $this->notes[] = $note;
        return $this;
    }

    public function notes($notes = null)
    {
        if ($notes !== null) {
            $this->notes = array();
            foreach ((array)$notes as $note) {
                if ($note instanceof ConversationNote) {
                    $this->notes[] = $note;
                }
            }
            return $this;
        }
        return $this->notes;
    }

    public function clearNotes()
    {
        $this->notes = array();
        return $this;
    }

    public function metadata($key = null, $value = null)
    {
        if ($key === null) {
            return $this->metadata;
        }
        if (is_array($key)) {
            $this->metadata = $key;
            return $this;
        }
        if (func_num_args() > 1) {
            $this->metadata[$key] = $value;
            return $this;
        }
        return isset($this->metadata[$key]) ? $this->metadata[$key] : null;
    }

    public function toArray()
    {
        $notes = array();
        foreach ($this->notes() as $note) {
            $notes[] = $note->toArray();
        }

        return array(
            'title' => $this->title(),
            'summary' => $this->summary(),
            'notes' => $notes,
            'metadata' => $this->metadata(),
        );
    }
}
