<?php

namespace Velis\Lang\Services;

use Velis\App;
use Velis\Lang\Dictionary;
use Velis\Lang\LangVariant;

class ClearLangsService
{
    /**
     * key - alias for core command
     * value - name of core command
     * @var string[]
     */
    protected static $optionAliases = [
        'dojo' => 'layout',
    ];


    /**
     * @var LangVariant[]
     */
    protected array $langVariants;

    public function __construct(array $langVariants = [])
    {
        $this->langVariants = $langVariants;
    }

    /**
     * @param string $option
     */
    public function refresh(string $option): void
    {
        $option = $this->prepareOption($option);

        switch ($option) {
            case 'mobile':
                $this->refreshMobile();
                break;

            case 'layout':
                $this->refreshLayout();
                break;

            case 'js':
                $this->refreshJs();
                break;

            default:
                $this->refreshMobile();
                $this->refreshLayout();
                $this->refreshJs();
                break;
        }

        App::consoleLog("* Langs have been refresh successfully!", true);
    }

    /**
     * @param string $option
     * @return string
     */
    private function prepareOption(string $option): string
    {
        $option = mb_strtolower(trim($option));

        if (array_key_exists($option, self::$optionAliases)) {
            return self::$optionAliases[$option];
        }

        return $option;
    }

    private function refreshLayout(): void
    {
        App::consoleLog("* Layout langs...");
        $dictionary = new Dictionary(Dictionary::LAYOUT, $this->langVariants);
        $dictionary->refresh(true);
        App::consoleLog("[done]", true);
    }

    private function refreshMobile(): void
    {
        if (!App::hasModule('Mobile')) {
            App::consoleLog("* Mobile langs is not available");

            return;
        }

        App::consoleLog("* Mobile langs...");
        $dictionary = new Dictionary(Dictionary::MOBILE, $this->langVariants);
        $dictionary->refresh(true);
        $JSONDictionary = new Dictionary(Dictionary::JSON, $this->langVariants);
        $JSONDictionary->refresh(true);
        App::consoleLog("[done]", true);
    }

    private function refreshJs(): void
    {
        App::consoleLog("* i18n langs...");
        $dictionary = new Dictionary(Dictionary::I18NEXT, $this->langVariants);
        $dictionary->refresh(true);
        App::consoleLog("[done]", true);
    }
}
