<?php

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

namespace Dotclear\Module;

use Autoloader;
use Dotclear\App;
use Dotclear\Helper\File\Files;
use Dotclear\Helper\File\Path;
use Dotclear\Interface\Core\ThemesInterface;
use Exception;

/**
 * @brief   Themes specific handler.
 *
 * An instance of this class is provided by App::themes()
 * and used for themes.
 *
 * @since   2.6
 */
class Themes extends Modules implements ThemesInterface
{
    protected ?string $type = 'theme';

    protected function loadModulesContext(array $ignored, string $ns, ?string $lang): void
    {
        if ($ns === 'admin' && App::blog()->isDefined()) {
            // Load current theme Backend process (and its parent)
            $theme = App::blog()->settings()->get('system')->getStr('theme', false);
            if ($theme !== '') {
                $this->loadNsFile($theme, 'admin');
            }
        }
    }

    /**
     * This method registers a theme in modules list.
     *
     * <var>$parent</var> is a optional value to indicate them inheritance.
     *
     * <var>$priority</var> is an integer. Modules are sorted by priority and name.
     * Lowest priority comes first. This property is currently ignored when dealing
     * with themes.
     *
     * @param      string  $name        The name
     * @param      string  $desc        The description
     * @param      string  $author      The author
     * @param      string  $version     The version
     * @param      mixed   $properties  The properties
     */
    public function registerModule(string $name, string $desc, string $author, string $version, $properties = []): void
    {
        if (!$this->id) {
            return;
        }

        $define = new ModuleDefine($this->id);

        $define
            ->set('name', $name)
            ->set('desc', $desc)
            ->set('author', $author)
            ->set('version', $version)
        ;

        if (is_array($properties)) {
            foreach ($properties as $k => $v) {
                $define->set((string) $k, $v);
            }
        }

        // Fallback to legacy registerModule parameters
        if (!is_array($properties)) {
            $args       = func_get_args();
            $properties = [];
            if (isset($args[4])) {
                $define->set('parent', $args[4]);
            }

            if (isset($args[5]) && is_numeric($args[5])) {
                $define->set('priority', (int) $args[5]);
            }
        }

        $this->defineModule($define);
    }

    /**
     * Get protected modules list (comma separated list), usually modules distributed with Dotclear
     */
    public function getProtectedModules(): string
    {
        // Consider only those themes present in the themes folder of the current installation as protected themes
        $current_themes_path = rtrim((string) Path::real(App::blog()->themesPath()), '/');

        return $current_themes_path === Path::real(App::config()->dotclearRoot()) . '/themes' ?
            App::config()->distributedThemes() :
            '';
    }

    protected function defineModule(ModuleDefine $define): void
    {
        // Themes specifics properties
        $define->set('permissions', App::auth()->makePermissions([
            App::auth()::PERMISSION_ADMIN,
        ]));

        parent::defineModule($define);
    }

    public function cloneModule(string $id): void
    {
        $module = $this->getDefine($id);

        $root = (string) end($this->path); // Use last folder set in folders list (should be only one for theme)
        if (!is_dir($root) || !is_readable($root)) {
            throw new Exception(__('Themes folder unreachable.'));
        }

        $root = rtrim($root, DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR;
        if ((@dir($root)) === false) {
            throw new Exception(__('Themes folder unreadable.'));
        }

        $counter     = 0;
        $module_root = is_string($module_root = $module->get('root')) ? $module_root : '';
        $module_name = is_string($module_name = $module->get('name')) ? $module_name : $id;

        $new_dir = sprintf('%s_copy', $module_root);
        while (is_dir($new_dir)) {
            $new_dir = sprintf('%s_copy_%s', $module_root, ++$counter);
        }

        $new_name = $module_name . ($counter !== 0 ? sprintf(__(' (copy #%s)'), $counter) : __(' (copy)'));

        if (!is_dir($new_dir)) {
            try {
                // Create destination folder named $new_dir in themes folder
                Files::makeDir($new_dir, false);

                // Clone directories and files

                $content = Files::getDirList($module_root);

                if (is_array($content)) {
                    // Create sub directories if necessary
                    foreach ($content['dirs'] as $dir) {
                        $rel = substr($dir, strlen($module_root));
                        if ($rel !== '') {
                            Files::makeDir($new_dir . $rel);
                        }
                    }

                    // Copy files from source to destination
                    foreach ($content['files'] as $file) {
                        // Copy file
                        $rel = substr($file, strlen($module_root));
                        copy($file, $new_dir . $rel);

                        if ($rel === (DIRECTORY_SEPARATOR . self::MODULE_FILE_DEFINE)) {
                            $buf = (string) file_get_contents($new_dir . $rel);
                            // Find offset of registerModule function call
                            $pos = (int) strpos($buf, '$this->registerModule');
                            // Change theme name to $new_name in _define.php
                            if (preg_match('/(\$this->registerModule\(\s*)((\s*|.*)+?)(\s*\);+)/m', $buf, $matches)) {
                                // Change only first occurence in registerModule parameters (should be the theme name)
                                $matches[2] = preg_replace('/' . preg_quote($module_name, '/') . '/', $new_name, $matches[2], 1);
                                $buf        = substr($buf, 0, $pos) . $matches[1] . $matches[2] . $matches[4];
                                $buf .= sprintf("\n\n// Cloned on %s from %s theme.\n", date('c'), $module_name);
                                file_put_contents($new_dir . $rel, $buf);
                            } else {
                                throw new Exception(__('Unable to modify _define.php.'));
                            }
                        }

                        if (str_ends_with($rel, '.php')) {
                            // Change namespace in *.php
                            $buf      = (string) file_get_contents($new_dir . $rel);
                            $prefixes = [
                                'themes\\',             // ex: namespace themes\berlin; → namespace themes\berlin_Copy; Dotclear <= 2.24
                                'Dotclear\Theme\\',     // ex: namespace Dotclear\Theme\Berlin; → namespace Dotclear\Theme\Berlin_Copy;
                            ];
                            foreach ($prefixes as $prefix) {
                                if (preg_match('/^namespace\s*' . preg_quote($prefix, '/') . '([^;].*);$/m', $buf, $matches)) {
                                    $pos     = (int) strpos($buf, $matches[0]);
                                    $rel_dir = substr($new_dir, strlen($root));
                                    $ns      = preg_replace('/\W/', '', str_replace(['-', '.'], '', $rel_dir));
                                    $buf     = substr($buf, 0, $pos) .
                                        'namespace ' . $prefix . $ns . ';' .
                                        substr($buf, $pos + strlen($matches[0]));
                                    file_put_contents($new_dir . $rel, $buf);

                                    break;
                                }
                            }
                        }
                    }
                }
            } catch (Exception $e) {
                Files::deltree($new_dir);

                throw new Exception($e->getMessage(), (int) $e->getCode(), $e);
            }
        } else {
            throw new Exception(__('Destination folder already exists.'));
        }
    }

    /**
     * Loads namespace <var>$ns</var> specific file for module with ID <var>$id</var>.
     *
     * Note: currently, only 'public' and 'admin' namespace is supported with themes.
     *
     * @param      string  $id     Module ID
     * @param      string  $ns     Namespace name
     */
    public function loadNsFile(string $id, ?string $ns = null): void
    {
        $define = $this->getDefine($id, ['state' => ModuleDefine::STATE_ENABLED]);
        if (!$define->isDefined() || !in_array($ns, ['admin', 'public'], true)) {
            return;
        }

        switch ($ns) {
            case 'admin':
                $class = self::MODULE_CLASS_ADMIN;
                $file  = self::MODULE_FILE_ADMIN;

                break;
            case 'public':
                $class = self::MODULE_CLASS_PUPLIC;
                $file  = self::MODULE_FILE_PUBLIC;

                break;
            default:
                return;
        }

        $theme_parent = is_string($theme_parent = $define->get('parent')) ? $theme_parent : '';
        if ($theme_parent !== '') {
            $parent = $this->getDefine($theme_parent, ['state' => ModuleDefine::STATE_ENABLED]);
            if ($parent->isDefined() && $this->loadNsClass($parent->getId(), $class) === '') {
                // by file name rather than by class name
                $parent_root = is_string($parent_root = $parent->get('root')) ? $parent_root : '';
                if ($parent_root !== '') {
                    $this->loadModuleFile($parent_root . DIRECTORY_SEPARATOR . $file, true);
                }
            }
        }

        // Check if there is a customized version of requested class
        $theme = App::blog()->settings()->get('system')->getStr('theme', false);
        if ($theme !== '') {
            $root = App::config()->varRoot() . DIRECTORY_SEPARATOR . 'themes' . DIRECTORY_SEPARATOR . App::blog()->id() . DIRECTORY_SEPARATOR . $theme;

            if (file_exists($root . DIRECTORY_SEPARATOR . self::MODULE_CLASS_DIR . DIRECTORY_SEPARATOR . $class . '.php')) {
                // Add supplemental source for this class
                $namespace = is_string($namespace = $define->get('namespace')) ? $namespace : '';
                if ($namespace !== '') {
                    Autoloader::me()->addNamespace($namespace, $root . DIRECTORY_SEPARATOR . self::MODULE_CLASS_DIR, true);
                    if ($this->loadNsClass($id, $class) !== '') {
                        return;
                    }
                }
            }

            if ($this->loadNsClass($id, $class) === '') {
                // by file name rather than by class name
                $customized = App::config()->varRoot() . DIRECTORY_SEPARATOR . 'themes' . DIRECTORY_SEPARATOR . App::blog()->id() . DIRECTORY_SEPARATOR . $theme . DIRECTORY_SEPARATOR . $file;
                // Check if there is customized version of requested file
                if (file_exists($customized)) {
                    $this->loadModuleFile($customized, true, false);
                } else {
                    $theme_root = is_string($theme_root = $define->get('root')) ? $theme_root : '';
                    $this->loadModuleFile($theme_root . DIRECTORY_SEPARATOR . $file, true);
                }
            }
        }
    }

    /**
     * Loads a theme locales.
     *
     * @param      string       $id     The identifier
     * @param      null|string  $lang   The language
     * @param      string       $file   The file
     */
    public function loadModuleL10N(string $id, ?string $lang, string $file): void
    {
        if ($this->safe_mode) {
            return;
        }

        $module = $this->getDefine($id);//, ['state' => ModuleDefine::STATE_ENABLED]);
        if ($lang && $module->isDefined()) {
            $template = '%s' . DIRECTORY_SEPARATOR . 'locales' . DIRECTORY_SEPARATOR . '%s' . DIRECTORY_SEPARATOR . '%s';
            $root     = is_string($root = $module->get('root')) ? $root : '';
            if ($root !== '' && App::lang()->set(sprintf($template, $root, $lang, $file)) === false && $lang !== 'en') {
                App::lang()->set(sprintf($template, $root, 'en', $file));
            }

            // Load also custom locales if any
            $root = App::config()->varRoot() . DIRECTORY_SEPARATOR . 'themes' . DIRECTORY_SEPARATOR . App::blog()->id() . DIRECTORY_SEPARATOR . $id;
            if (App::lang()->set(sprintf($template, $root, $lang, $file)) === false && $lang !== 'en') {
                App::lang()->set(sprintf($template, $root, 'en', $file));
            }
        }
    }

    public function isOverloadable(string $id): bool
    {
        $module = $this->getDefine($id);

        return $module->isDefined();
    }
}
