<?php

namespace kernel\console\controllers;

use kernel\console\ConsoleController;
use kernel\helpers\Files;
use kernel\services\KernelService;
use ZipArchive;

class KernelController extends ConsoleController
{
    protected Files $files;

    public function __construct()
    {
        parent::__construct();
        $this->files = new Files();
    }

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

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

            $tmpKernelDirFull = RESOURCES_DIR . '/tmp/ad/kernel/';

            $fileHelper = new Files();
            $fileHelper->copy_folder(KERNEL_DIR, $tmpKernelDirFull);

            $fileHelper->pack($tmpKernelDirFull, RESOURCES_DIR . '/tmp/kernel/kernel.itguild');

            $fileHelper->recursiveRemoveDir($tmpKernelDirFull);
            $this->out->r("Ядро заархивировано", 'green');
        } else {
            $this->out->r("Ядро не найдено", 'red');
        }
    }

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

        $path = $this->argv['path'];

        if (file_exists(ROOT_DIR . $path)) {
            $zip = new ZipArchive;
            $tmpKernelDir = md5(time());
            $res = $zip->open(ROOT_DIR . $path);
            if ($res === TRUE) {
                $tmpKernelDirFull = RESOURCES_DIR . '/tmp/kernel/' . $tmpKernelDir . "/";
                $zip->extractTo($tmpKernelDirFull);
                $zip->close();
                $this->files->copy_folder($tmpKernelDirFull , ROOT_DIR . "/kernel");
                $this->files->recursiveRemoveDir($tmpKernelDirFull);
                $this->out->r('Ядро обновлено.', 'green');
            } else {
                $this->out->r('unable to open zip archive', 'red');
                return false;
            }
        } else {
            $this->out->r("Модуль не найден", 'red');
        }
    }

    public function test()
    {

    }

}