<?php

namespace kernel\console\controllers;

use kernel\console\ConsoleController;
use kernel\helpers\Files;
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/kernel';
            $this->files->copy_folder(ROOT_DIR . $this->argv['path'], $tmpKernelDirFull);
            $this->out->r("Ядро скопировано во временную папку", 'green');
        } else {
            $this->out->r("Ядро не найдено", 'red');
        }

        if (file_exists(ROOT_DIR . '/bootstrap')) {
            $tmpBootstrapDirFull = RESOURCES_DIR . '/tmp/ad/kernel/bootstrap';
            $this->files->copy_folder(ROOT_DIR . '/bootstrap', $tmpBootstrapDirFull);
            $this->out->r("/bootstrap скопирован во временную папку", 'green');
        } else {
            $this->out->r("/bootstrap не найден", 'red');
        }

        if (file_exists(ROOT_DIR . '/bootstrap.php')) {
            $tmpBootstrapPhpDirFull = RESOURCES_DIR . '/tmp/ad/kernel/bootstrap.php';
            copy(ROOT_DIR . '/bootstrap.php', $tmpBootstrapPhpDirFull);
            $this->out->r("/bootstrap.php скопирован во временную папку", 'green');
        } else {
            $this->out->r("/bootstrap.php не найден", 'red');
        }

        if (file_exists(ROOT_DIR . '/.env.example')) {
            $tmpEnvDirFull = RESOURCES_DIR . '/tmp/ad/kernel/env.example';
            copy(ROOT_DIR . '/.env.example', $tmpEnvDirFull);
            $this->out->r("/.env.example скопирован во временную папку", 'green');
        } else {
            $this->out->r("/.env.example не найден", 'red');
        }

        if (file_exists(ROOT_DIR . '/composer.json')) {
            $tmpComposerDirFull = RESOURCES_DIR . '/tmp/ad/kernel/composer.json';
            copy(ROOT_DIR . '/composer.json', $tmpComposerDirFull);
            $this->out->r("/composer.json скопирован во временную папку", 'green');
        } else {
            $this->out->r("/composer.json не найден", 'red');
        }

        if (!is_dir(RESOURCES_DIR . '/tmp/kernel')) {
            mkdir(RESOURCES_DIR . '/tmp/kernel');
        }

        if (file_exists(KERNEL_DIR . '/manifest.json')) {
            $manifest = json_decode(file_get_contents(KERNEL_DIR . '/manifest.json'), true);
            $version = $manifest['version'] ?? '';
            $this->files->pack(RESOURCES_DIR . '/tmp/ad/kernel/', RESOURCES_DIR . '/tmp/kernel/kernel_v' . $version . '.igk');
        }
        else {
            $this->files->pack(RESOURCES_DIR . '/tmp/ad/kernel/', RESOURCES_DIR . '/tmp/kernel/kernel.igk');
        }

        $this->files->recursiveRemoveDir(RESOURCES_DIR . '/tmp/ad/kernel/');
    }

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

        $zip = new ZipArchive;
        if (file_exists(ROOT_DIR . $this->argv['path'])) {
            $tmpKernelDir = md5(time());
            $res = $zip->open(ROOT_DIR . $this->argv['path']);
            if ($res === TRUE) {
                $tmpKernelDirFull = RESOURCES_DIR . '/tmp/kernel/' . $tmpKernelDir . "/";
                $zip->extractTo($tmpKernelDirFull);
                $zip->close();
                $this->files->recursiveRemoveKernelDir();
                $this->files->copy_folder($tmpKernelDirFull . 'kernel' , ROOT_DIR . "/kernel");

                if (isset($this->argv['bootstrap'])) {
                    $this->files->recursiveRemoveDir(ROOT_DIR . '/bootstrap');
                    $this->files->copy_folder($tmpKernelDirFull . 'bootstrap' , ROOT_DIR . '/bootstrap');
                    copy($tmpKernelDirFull . '/bootstrap.php' , ROOT_DIR . '/bootstrap.php');
                }

                if (isset($this->argv['env'])) {
                    copy($tmpKernelDirFull . 'env.example', ROOT_DIR . '/.env.example');
                }

                if (isset($this->argv['composer'])) {
                    copy($tmpKernelDirFull . 'composer.json', ROOT_DIR . '/composer.json');
                }

                $this->files->recursiveRemoveDir($tmpKernelDirFull);
                $this->out->r('Ядро обновлено.', 'green');
            } else {
                $this->out->r('unable to open zip archive', 'red');
            }
        } else {
            $this->out->r("archive not found", 'red');
        }
    }

}