<?php
/**
 * For the full copyright and license information, please view the
 * docs/licenses/LICENSE.txt file that was distributed with this source code.
 */

declare(strict_types=1);

namespace PrestaShop\PrestaShop\Core\Module;

use Doctrine\Common\Cache\CacheProvider;
use Module as ModuleLegacy;
use PrestaShop\PrestaShop\Adapter\Entity\Shop;
use PrestaShop\PrestaShop\Adapter\HookManager;
use PrestaShop\PrestaShop\Adapter\Module\AdminModuleDataProvider;
use PrestaShop\PrestaShop\Adapter\Module\Module;
use PrestaShop\PrestaShop\Adapter\Module\ModuleDataProvider;
use PrestaShop\PrestaShop\Core\Context\LanguageContext;
use PrestaShop\PrestaShop\Core\Domain\Module\Exception\ModuleNotFoundException;
use PrestaShop\PrestaShop\Core\Domain\Profile\Permission\ValueObject\ModulePermission;
use PrestaShop\PrestaShop\Core\Util\PHPCli;
use Symfony\Component\Finder\Finder;
use Throwable;

class ModuleRepository implements ModuleRepositoryInterface
{
    private const MODULE_ATTRIBUTES = [
        'warning',
        'name',
        'tab',
        'displayName',
        'description',
        'additional_description',
        'author',
        'limited_countries',
        'need_instance',
        'confirmUninstall',
    ];

    /** @var ModuleDataProvider */
    private $moduleDataProvider;

    /** @var AdminModuleDataProvider */
    private $adminModuleDataProvider;

    /** @var HookManager */
    private $hookManager;

    /** @var CacheProvider */
    private $cacheProvider;

    /** @var string */
    private $modulePath;

    /** @var array|null */
    private $installedModules;

    /** @var Module[] */
    private $modulesFromHook;

    public function __construct(
        ModuleDataProvider $moduleDataProvider,
        AdminModuleDataProvider $adminModuleDataProvider,
        CacheProvider $cacheProvider,
        HookManager $hookManager,
        string $modulePath,
        private LanguageContext $languageContext,
    ) {
        $this->moduleDataProvider = $moduleDataProvider;
        $this->adminModuleDataProvider = $adminModuleDataProvider;
        $this->cacheProvider = $cacheProvider;
        $this->hookManager = $hookManager;
        $this->modulePath = $modulePath;
    }

    public function getList(): ModuleCollection
    {
        $modules = new ModuleCollection();
        $modulesDirsList = (new Finder())->directories()
            ->in($this->modulePath)
            ->depth('== 0')
            ->exclude(['__MACOSX'])
            ->ignoreVCS(true);

        foreach ($modulesDirsList as $moduleDir) {
            $moduleName = $moduleDir->getFilename();
            if (null === $this->getModulePath($moduleName)) {
                continue;
            }

            $modules->add($this->getModule($moduleName));
        }

        $modules = $this->addModulesFromHook($modules);

        return $this->filterModulesByPermissions($modules);
    }

    public function getInstalledModules(): ModuleCollection
    {
        return $this->getList()->filter(static function (Module $module) {
            return $module->isInstalled();
        });
    }

    public function getMustBeConfiguredModules(): ModuleCollection
    {
        return $this->getList()->filter(static function (Module $module) {
            return $module->isConfigurable() && $module->isActive() && $module->hasValidInstance() && !empty($module->getInstance()->warning);
        });
    }

    /**
     * Returns an instance of a present module, if the module is not in the modules folder an exception is thrown.
     */
    public function getPresentModule(string $technicalName): Module
    {
        $module = $this->getModule($technicalName);
        if (!$module->disk->get('is_present')) {
            throw new ModuleNotFoundException();
        }

        return $module;
    }

    public function getUpgradableModules(): ModuleCollection
    {
        return $this->getList()->filter(static function (Module $module) {
            return $module->canBeUpgraded();
        });
    }

    /**
     * @param string $moduleName
     *
     * @return Module
     */
    public function getModule(string $moduleName): ModuleInterface
    {
        $filePath = $this->getModulePath($moduleName);

        $filemtime = $filePath === null
            ? 0
            : (int) @filemtime($filePath);

        $cacheKey = $this->getCacheKey($moduleName);

        if ($this->cacheProvider->contains($cacheKey)) {
            /** @var Module $module */
            $module = $this->cacheProvider->fetch($cacheKey);
            if ($module->getDiskAttributes()->get('filemtime') === $filemtime) {
                return $this->enrichModuleAttributesFromHook($module);
            }
        }

        $isValid = $filemtime > 0 && $this->moduleDataProvider->isModuleMainClassValid($moduleName);
        $attributes = $this->getModuleAttributes($moduleName, $isValid);
        if (empty($attributes)) {
            $isValid = false;
        }
        $attributes = array_merge(['name' => $moduleName], $attributes);
        $disk = $this->getModuleDiskAttributes($moduleName, $isValid, $filemtime);
        $database = $this->getModuleDatabaseAttributes($moduleName);

        $coreModule = new Module($attributes, $disk, $database);
        $this->cacheProvider->save($cacheKey, $coreModule);

        return $this->enrichModuleAttributesFromHook($coreModule);
    }

    public function getModulePath(string $moduleName): ?string
    {
        $path = $this->modulePath . '/' . $moduleName;
        $filePath = $path . '/' . $moduleName . '.php';

        if (!is_file($filePath)) {
            return null;
        }

        return $path;
    }

    public function setActionUrls(ModuleCollection $collection): ModuleCollection
    {
        return $this->adminModuleDataProvider->setActionUrls($collection);
    }

    /**
     * @param string|null $moduleName The module to clear the cache for. If the name is null, the cache will be cleared for all modules.
     * @param bool $allShops Default to false. If the value is true, the cache will be cleared for all the active shops. If not it will be cleared only for the shop in the context.
     *
     * @return bool
     */
    public function clearCache(?string $moduleName = null, bool $allShops = false): bool
    {
        $this->installedModules = null;
        if ($moduleName !== null) {
            if ($allShops) {
                foreach (Shop::getShops(true, null, true) as $shopId) {
                    $cacheKey = $this->getCacheKey($moduleName, $shopId);
                    if ($this->cacheProvider->contains($cacheKey)) {
                        if (!$this->cacheProvider->delete($cacheKey)) {
                            return false;
                        }
                    }
                }
            }

            $cacheKey = $this->getCacheKey($moduleName);
            if ($this->cacheProvider->contains($cacheKey)) {
                return $this->cacheProvider->delete($cacheKey);
            }
        }

        return $this->cacheProvider->deleteAll();
    }

    /**
     * @param string $moduleName
     * @param int|null $shopId If this parameter is given, the key returned will be the one for the shop. Otherwise, it will be the cache key for the shop in the context.
     *
     * @return string
     */
    protected function getCacheKey(string $moduleName, ?int $shopId = null): string
    {
        $shop = $shopId ? [$shopId] : Shop::getContextListShopID();

        return $moduleName . implode('-', $shop) . $this->languageContext->getId();
    }

    private function getModuleAttributes(string $moduleName, bool $isValid): array
    {
        $attributes = [];
        if ($isValid) {
            try {
                $tmpModule = ModuleLegacy::getInstanceByName($moduleName);
            } catch (Throwable) {
                return $attributes;
            }
            foreach (self::MODULE_ATTRIBUTES as $attribute) {
                if (isset($tmpModule->{$attribute})) {
                    $attributes[$attribute] = $tmpModule->{$attribute};
                }
            }
            $attributes['parent_class'] = get_parent_class($tmpModule);
            $attributes['is_paymentModule'] = is_subclass_of($tmpModule, 'PaymentModule');
            $attributes['is_configurable'] = method_exists($tmpModule, 'getContent');
        }

        return $attributes;
    }

    private function getModuleDiskAttributes(string $moduleName, bool $isValid, int $filemtime): array
    {
        $path = $this->modulePath . $moduleName;
        if ($isValid) {
            $version = ModuleLegacy::getModuleVersion($moduleName) ?: null;
        } else {
            $version = null;
        }

        return [
            'filemtime' => $filemtime,
            'is_present' => $filemtime > 0,
            'is_valid' => $isValid,
            'version' => $version,
            'path' => $path,
        ];
    }

    private function getModuleDatabaseAttributes(string $moduleName): array
    {
        if ($this->installedModules === null) {
            $this->installedModules = $this->moduleDataProvider->getInstalled();
        }

        return $this->installedModules[$moduleName] ?? [];
    }

    /**
     * @return array
     */
    private function getModulesFromHook()
    {
        if ($this->modulesFromHook === null) {
            // An array [module_name => module_output] will be returned
            $modulesFromHook = $this->hookManager->exec('actionListModules', [], null, true);
            $modulesFromHook = array_values($modulesFromHook ?? []);

            // Merge hooks from modules if it's an array and not empty
            $filteredModulesFromHook = array_filter($modulesFromHook, function ($item) { return is_array($item); });
            $this->modulesFromHook = empty($filteredModulesFromHook) ? [] : array_merge(...$filteredModulesFromHook);
        }

        return $this->modulesFromHook;
    }

    /**
     * @param ModuleCollection $modules
     *
     * @return ModuleCollection
     */
    protected function addModulesFromHook(ModuleCollection $modules): ModuleCollection
    {
        try {
            $externalModules = $this->getModulesFromHook();
        } catch (Throwable $e) {
            $modules->addError($e);

            return $modules;
        }

        foreach ($externalModules as $externalModule) {
            $merged = false;
            foreach ($modules as $module) {
                if ($module->get('name') === $externalModule['name']) {
                    $merged = true;
                    break;
                }
            }
            if (!$merged) {
                $modules->add(new Module($externalModule));
            }
        }

        return $modules;
    }

    /**
     * @param Module $module
     *
     * @return Module
     */
    protected function enrichModuleAttributesFromHook(Module $module): ModuleInterface
    {
        try {
            $modulesFromHook = $this->getModulesFromHook();
        } catch (Throwable) {
            return $module;
        }

        foreach ($modulesFromHook as $moduleFromHook) {
            if ($module->get('name') === $moduleFromHook['name']) {
                $moduleVersionAvailable = $module->getAttributes()->get('version_available');
                $moduleHookVersionAvailable = $moduleFromHook['version_available'];
                // We keep the more up-to-date information (in case multiple sources provide the same module)
                if (!empty($moduleVersionAvailable) && !empty($moduleHookVersionAvailable) && version_compare($moduleVersionAvailable, $moduleHookVersionAvailable, '>')) {
                    continue;
                }

                // Prevent data from hooks from overriding local translations on displayName and description
                if ($module->attributes->has('displayName') && !empty($module->attributes->get('displayName'))) {
                    unset($moduleFromHook['displayName']);
                }
                if ($module->attributes->has('description') && !empty($module->attributes->get('description'))) {
                    unset($moduleFromHook['description']);
                }

                $module->getAttributes()->add($moduleFromHook);
            }
        }

        return $module;
    }

    /**
     * Filter modules if the current employee has the right to see it.
     *
     * Skipped when running in CLI: there is no logged-in employee in that
     * context, so the per-employee permission check has no meaning and would
     * otherwise hide every installed module from console commands.
     */
    protected function filterModulesByPermissions(ModuleCollection $modules): ModuleCollection
    {
        if (PHPCli::isPHPCli()) {
            return $modules;
        }

        foreach ($modules as $key => $module) {
            $moduleName = $module->getAttributes()->get('name');
            if ($this->moduleDataProvider->isInstalled($moduleName)
                && !$this->moduleDataProvider->can(
                    ModulePermission::VIEW,
                    $moduleName
                )) {
                unset($modules[$key]);
            }
        }

        return $modules;
    }
}
