<?php

/**
 * @package     Dotclear
 *
 * @copyright   Olivier Meunier & Association Dotclear
 * @copyright   AGPL-3.0
 */
declare(strict_types=1);

namespace Dotclear\Plugin\themeEditor;

use Dotclear\App;
use Dotclear\Helper\Html\Form\Checkbox;
use Dotclear\Helper\Html\Form\Div;
use Dotclear\Helper\Html\Form\Fieldset;
use Dotclear\Helper\Html\Form\Hidden;
use Dotclear\Helper\Html\Form\Label;
use Dotclear\Helper\Html\Form\Legend;
use Dotclear\Helper\Html\Form\Link;
use Dotclear\Helper\Html\Form\Optgroup;
use Dotclear\Helper\Html\Form\Option;
use Dotclear\Helper\Html\Form\Para;
use Dotclear\Helper\Html\Form\Select;
use Dotclear\Helper\Html\Form\Text;
use Exception;

/**
 * @brief   The module backend behaviors.
 * @ingroup themeEditor
 */
class BackendBehaviors
{
    /**
     * Add an editor button (if possible).
     */
    public static function adminCurrentThemeDetails(): string
    {
        // Check permission before allowing modification
        if (App::auth()->isSuperAdmin()) {
            return (new Para())
                ->items([
                    (new Link())
                        ->href(My::manageUrl())
                        ->class('button')
                        ->text(__('Edit theme files')),
                ])
            ->render();
        }

        return '';
    }

    /**
     * Save user preferences, color syntax activation and its theme.
     */
    public static function adminBeforeUserUpdate(): string
    {
        // Get and store user's prefs for plugin options
        try {
            App::auth()->prefs()->get('interface')->put('colorsyntax', !empty($_POST['colorsyntax']), App::userWorkspace()::WS_BOOL);
            App::auth()->prefs()->get('interface')->put(
                'colorsyntax_theme',
                (empty($_POST['colorsyntax_theme']) ? '' : $_POST['colorsyntax_theme']),
                App::userWorkspace()::WS_STRING
            );
        } catch (Exception $exception) {
            App::error()->add($exception->getMessage());
        }

        return '';
    }

    /**
     * Display user preferences, color syntax activation and theme selection.
     */
    public static function adminPreferencesForm(): string
    {
        // Add fieldset for plugin options
        $current_theme = App::auth()->prefs()->get('interface')->getStr('colorsyntax_theme') ?? 'default';

        /**
         * @var array<array-key, array<array-key, string>> $themes_list (0 = light, 1 = dark)
         */
        $themes_list = App::backend()->page()->getCodeMirrorThemes(true);

        // Capitalize each word, replace dash by space, add a space before numbers
        $sanitizeThemeName = fn (string $theme_id): string => (string) preg_replace('/(\d+)/', ' $1', ucwords(str_replace(['-', '.', '_'], ' ', $theme_id)));

        $themes_combo_light = [... array_map(fn (string $value): Option => new Option(trim($sanitizeThemeName($value)), $value), $themes_list[0])];
        $themes_combo_dark  = [... array_map(fn (string $value): Option => new Option(trim($sanitizeThemeName($value)), $value), $themes_list[1])];

        $themes_combo = [
            new Option(__('Default'), ''),
        ];
        if ($themes_combo_light !== []) {
            $themes_combo[] = (new Optgroup(__('Light themes')))->items($themes_combo_light);
        }

        if ($themes_combo_dark !== []) {
            $themes_combo[] = (new Optgroup(__('Dark themes')))->items($themes_combo_dark);
        }

        $sample = '
<textarea id="codemirror" name="codemirror" readonly="true">
// program to convert celsius to fahrenheit
// ask the celsius value to the user
const celsius = prompt("Enter a celsius value: ");

// calculate fahrenheit
const fahrenheit = (celsius * 1.8) + 32

// display the result
console.log(`${celsius} degree celsius is equal to ${fahrenheit} degree fahrenheit.`);
</textarea>';

        $codemirror = App::backend()->page()->jsLoadCodeMirror('', false, ['javascript']);
        if ($current_theme !== 'default') {
            $codemirror .= App::backend()->page()->cssLoad('js/codemirror/theme/' . $current_theme . '.css');
        }

        $codemirror .= App::backend()->page()->jsJson('theme_editor_current', ['theme' => $current_theme]) . My::jsLoad('theme');

        echo (new Fieldset())
            ->id('themeEditor_prefs')
            ->legend(new Legend(__('Syntax highlighting')))
            ->fields([
                (new Div())
                    ->class('two-cols')
                    ->items([
                        (new Div())
                            ->class('col30')
                            ->items([
                                (new Para())
                                    ->items([
                                        (new Checkbox('colorsyntax', App::auth()->prefs()->get('interface')->getBool('colorsyntax', false)))
                                            ->value(1)
                                            ->label(new Label(__('Syntax highlighting in theme editor'), Label::IL_FT)),
                                    ]),
                                (
                                    count($themes_combo) > 1 ?
                                    (new Para())->items([
                                        (new Select('colorsyntax_theme'))
                                            ->default($current_theme)
                                            ->items($themes_combo)
                                            ->label(new Label(__('Theme:'), Label::IL_TF)),
                                    ]) :
                                    (new Hidden('colorsyntax_theme', ''))
                                ),
                            ]),
                        (new Div())
                            ->class('col70')
                            ->items([
                                (new Text(null, $codemirror)),
                                (new Text(null, trim($sample))),
                            ]),
                    ]),
            ])
        ->render();

        return '';
    }
}
