<?php

namespace kernel\console\controllers;

use kernel\console\ConsoleController;
use kernel\helpers\Debug;
use kernel\helpers\Files;
use kernel\helpers\Manifest;
use kernel\models\Option;
use ZipArchive;
use kernel\services\ModuleService;

class ModuleController extends ConsoleController
{

    /**
     * @throws \Exception
     */
    public function actionInstallModule(): void
    {
        if (!isset($this->argv['path'])) {
            throw new \Exception('Missing module path "--path" specified');
        }

        $zip = new ZipArchive;
        $tmpModuleDir = md5(time());
        $res = $zip->open(ROOT_DIR . $this->argv['path']);
        if ($res === TRUE) {
            $tmpModuleDirFull = RESOURCES_DIR . '/tmp/ad/' . $tmpModuleDir . "/";
            $zip->extractTo($tmpModuleDirFull);
            $zip->close();
            $this->out->r('Архив распакован', 'green');
        } else {
            $this->out->r('Message: Ошибка чтения архива', 'red');
        }

        if (file_exists($tmpModuleDirFull . "manifest.json")){
            $manifestJson = getConst(file_get_contents($tmpModuleDirFull . "manifest.json"));
            $manifest = Manifest::getWithVars($manifestJson);
            $this->out->r('manifest.json инициализирован', 'green');

            $fileHelper = new Files();
            $fileHelper->copy_folder($tmpModuleDirFull, $manifest['module_path']);

            $this->out->r("Удаляем временные файлы", 'green');
            $fileHelper->recursiveRemoveDir($tmpModuleDirFull);

            $this->out->r("Модуль " . $manifest['name'] . " установлен", 'green');
        }
    }

    /**
     * @throws \Exception
     */
    public function actionUninstallModule(): void
    {
        if (!isset($this->argv['path'])) {
            throw new \Exception('Missing module path "--path" specified');
        }

        if (file_exists(ROOT_DIR . $this->argv['path'])) {
            $moduleService = new ModuleService();
            $moduleInfo = $moduleService->getModuleInfo(ROOT_DIR . $this->argv['path']);

            if ($moduleService->isActive($moduleInfo['slug'])) {
                $moduleService->setActiveModule($moduleInfo['slug']);
            }

            $fileHelper = new Files();
            $fileHelper->recursiveRemoveDir(ROOT_DIR . $this->argv['path']);

            $this->out->r("Модуль удален", 'green');
        } else {
            var_dump($this->argv['path']);
            $this->out->r("Модуль не найден", 'red');
        }
    }

    public function actionPackModule(): void
    {
        if (!isset($this->argv['path'])) {
            throw new \Exception('Missing module path "--path" specified');
        }

        if (file_exists(ROOT_DIR . $this->argv['path'])) {
            $moduleName = basename($this->argv['path']);

            $tmpModuleDirFull = RESOURCES_DIR . '/tmp/ad/' . $moduleName . "/";

            $fileHelper = new Files();
            $fileHelper->copy_folder(APP_DIR . '/modules/' . $moduleName, $tmpModuleDirFull . 'app/');
            $fileHelper->copy_folder(KERNEL_APP_MODULES_DIR . '/' . $moduleName, $tmpModuleDirFull . 'kernel/');

            $this->out->r("Модуль собран в одну папку", 'green');


//            $fileHelper->pack($zip, RESOURCES_DIR . '/tmp/modules/' . $moduleName . '.zip');
            $fileHelper->pack($tmpModuleDirFull, RESOURCES_DIR . '/tmp/modules/' . $moduleName . '.zip');

//            $zip->addEmptyDir($moduleName);
//            $zip->close();
//            $this->out->r("zip закрыт", 'green');

            $this->out->r("Архив создан", 'green');

        }
    }

}