<?php

namespace engine\lang;

class Strings extends StringsBase
{
    private static ?Strings $instance = null;
    protected array $loadedLangPacks = [];

    private function __construct() {}

    protected function __clone() {}

    public static function getInstance(): Strings {
        if (is_null(self::$instance)) {
            self::$instance = new self();
        }
        return self::$instance;
    }

    public function load(string|StringsPack ...$packs): array {
        $keys = [];
        foreach ($packs as $arg) {
            if ($arg instanceof StringsPack)
                $raw = $arg->getData();
            else {
                // TODO implement proper cache in StringsPack class
                if (isset($this->loadedLangPacks[$arg]))
                    continue;
                $raw = self::getStringsPack($arg, true);
            }
            $this->data = array_merge($this->data, $raw);
            $keys = array_merge($keys, array_keys($raw));
            $this->loadedLangPacks[$arg] = true;
        }
        return $keys;
    }

    /**
     * @param string $name Pack name.
     * @param bool $raw Whether to return raw data.
     * @return array<string,string|string[]>|StringsPack 
     */
    public static function getStringsPack(string $name, bool $raw = false): array|StringsPack {
        $file = APP_ROOT.'/src/strings/'.$name.'.yaml';
        $data = yaml_parse_file($file);
        if ($data === false)
            logError(__METHOD__.': yaml_parse_file failed on file '.$file);
        return $raw ? $data : new StringsPack($data);
    }

    public function search(string $regexp): array {
        return preg_grep($regexp, array_keys($this->data));
    }
}
