<?php

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

namespace Dotclear\Plugin\widgets;

use Dotclear\App;
use Dotclear\Helper\Process\TraitProcess;
use Exception;

/**
 * @brief   The module install process.
 * @ingroup widgets
 */
class Install
{
    use TraitProcess;

    public static function init(): bool
    {
        return self::status(My::checkContext(My::INSTALL));
    }

    public static function process(): bool
    {
        if (!self::status()) {
            return false;
        }

        if (class_exists(__NAMESPACE__ . '\Widgets')) {
            Widgets::init();
        } else {
            throw new Exception(__('Unable to initialize default widgets.'));
        }

        /**
         * @todo Verify if this init is required
         */
        $s = My::settings();
        if ($s->get('widgets_nav') !== null) {
            $s->put('widgets_nav', WidgetsStack::load($s->get('widgets_nav'))->store());
        } else {
            $s->put('widgets_nav', [], App::blogWorkspace()::NS_ARRAY, 'Navigation widgets', false);
        }

        if ($s->get('widgets_extra') !== null) {
            $s->put('widgets_extra', WidgetsStack::load($s->get('widgets_extra'))->store());
        } else {
            $s->put('widgets_extra', [], App::blogWorkspace()::NS_ARRAY, 'Extra widgets', false);
        }

        if ($s->get('widgets_custom') !== null) {
            $s->put('widgets_custom', WidgetsStack::load($s->get('widgets_custom'))->store());
        } else {
            $s->put('widgets_custom', [], App::blogWorkspace()::NS_ARRAY, 'Custom widgets', false);
        }

        return true;
    }
}
