<?php

namespace LaraBB\Translate\Actions;

use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use LaraBB\Translate\Tasks\GetLanguagesTask;
use LaraBB\Translate\Tasks\GetTranslationsTask;

/**
 * Class TranslatePageAction
 * @package LaraBB\Translate\Actions
 */
class TranslatePageAction
{
    /**
     * TranslatePageAction constructor.
     * @param GetTranslationsTask $getTranslationsTask
     * @param GetLanguagesTask $getLanguagesTask
     */
    public function __construct(
        private readonly GetTranslationsTask $getTranslationsTask,
        private readonly GetLanguagesTask $getLanguagesTask
    ) {

    }

    /**
     * @param Request $request
     * @param $lang
     * @return array|RedirectResponse
     */
    public function run(Request $request, $lang)
    {
        app()->setLocale(session('lang', 'en'));

        $languages         = $this->getLanguagesTask->run();
        $translations      = $this->getTranslationsTask->run();
        $translationKeys   = array_keys($translations->get('de'));
        $translationValues = $translations->has($lang) ? $translations->get($lang) : array_fill_keys($translationKeys, null);

        $progress = count(array_values(array_filter($translationValues))) / count($translationKeys) * 100;

        return [
            'languages'         => $languages,
            'translationKeys'   => $translationKeys,
            'translationValues' => $translationValues,
            'currentLang'       => $lang,
            'progress'          => $progress
        ];
    }
}
