<?php


namespace App\Command;

use Boa\GeneralBundle\Service\Mailer;
use Doctrine\Persistence\ManagerRegistry;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\HttpKernel\KernelInterface;
use Symfony\Contracts\Translation\TranslatorInterface;

class RefreshCommand extends Command
{
    private $kernel;

    public function __construct(KernelInterface $kernel)
    {
        $this->kernel = $kernel;
        parent::__construct();
    }
    protected function configure()
    {
        $this
            ->setName('refresh')
            ->setDescription('Cleanup runs')
            ->setHelp('This command cleans the runs table');
    }

    protected function execute(InputInterface $input, OutputInterface $output): int
    {
        $zip = $this->kernel->getCacheDir() . '/website.zip';
        $mddir = $this->kernel->getCacheDir() . '/pages';
        $assetdir = $this->kernel->getProjectDir() . '/public/assets/';
        file_put_contents($zip, file_get_contents($_ENV['DATADIR']));
        $zipobj = new \ZipArchive();
        $res = $zipobj->open($zip);
        if ($res === TRUE) {
            if(is_dir($mddir)) $this->recursiveRemoveDirectory($mddir);
            if(is_dir($assetdir)) $this->recursiveRemoveDirectory($assetdir);
            $zipobj->extractTo($this->kernel->getCacheDir());
            $zipobj->close();

            rename($this->kernel->getCacheDir() . '/Website/assets', $assetdir);
            rename($this->kernel->getCacheDir() . '/Website', $mddir);
            return Command::SUCCESS;
        }
        return Command::FAILURE;
    }

    function recursiveRemoveDirectory($dir)
    {

        $files = array_diff(scandir($dir), array('.', '..'));

        foreach ($files as $file) {
            (is_dir("$dir/$file")) ? $this->recursiveRemoveDirectory("$dir/$file") : unlink("$dir/$file");
        }

        return rmdir($dir);
    }
}