<?php

namespace Detektivo\Helper;

use Closure;

class Indexer extends \Lime\Helper {

    protected string $name;

    public static function init(string $name, $app) {
        $indexer = new static($name, $app);
    }

    public function __construct(string $name, $app) {
        parent::__construct($app);

        $this->name = $name;
    }

    public function start(array $meta = []): mixed {

        if ($this->isIndexerRunning()) {
            return null;
        }

        $detektivo = $this->app->module('detektivo');

        if (!$detektivo->exists($this->name)) {
            return null;
        }

        $index = $detektivo->indexes($this->name);
        $type = $detektivo->indexTypes($index['type']);

        if (!$type || !isset($type['index']) || !\is_callable($type['index'])) {
            return null;
        }

        $index['meta'] = \array_replace_recursive($index['meta'] ?? [], $meta);

        $idx = $detektivo->index($this->name);

        $callback = Closure::bind($type['index'], $this, $this);

        $this->log('Indexing started');

        $callback($index, $idx);

        $this->app->dataStorage->removeKey('detektivo/indexer', $this->name);

        return true;
    }

    public function isIndexerRunning(): bool {
        return $this->app->dataStorage->keyExists('detektivo/indexer', $this->name);
    }

    public function log(string $msg, string $type = 'info') {
        $this->app->dataStorage->rpush('detektivo/indexer', $this->name, ['time' => \time(), 'msg' => $msg, 'type' => $type]);
    }

    public function getLog(): ?array {
        return $this->app->dataStorage->getKey('detektivo/indexer', $this->name, []);
    }
}
