<?php

class MediaDB
{
    private $handler;
    private array $lines = [];

    // TODO: create a persist() method that updates the line if the offset where
    //       it originally existed in is given by 'ftell'. If it doesn't have
    //       an ID, then try to find it in the file and if it doesn't exist,
    //       append

    public function __construct()
    {
        // Just initialize the file handler
        $this->handler = fopen($GLOBALS['path_mediadb'], 'r');
        if ($this->handler === false)
            Json::error('Error opening media DB');
    }

    private function getLine(): ?array
    {
        $ret = fgetcsv($this->handler, 0, ' ');
        if ($ret === false)
            return null;

        return $ret;
    }

    public static function add(array|Item $item)
    {
        $file = fopen($GLOBALS['path_mediadb'], 'a+');
        if ($file === false)
            Json::error('Failed opening media DB for adding new Item')->die();

        $line = $item->getHash() . ' ' . implode(' ', $item->getTags());

        if (fwrite($file, $line . "\n") == false)
            Json::error('Write operation failed on Item adding')->die();

        fclose($file);

        // The $this->list will be updated on trying to find new items
    }

    public function map(callable $func)
    {
        // First read from what's already in memory
        foreach ($this->lines as $i_line) {
            if ($func($i_line) === true) return;
        }

        // If we run out, read from the file and append to array so the next
        // lookup is fast
        while ($line = $this->getLine()) {
            $this->lines[] = $line;

            if ($func($line) === true) return;
        }
    }
}