<?php

declare(strict_types=1);

/**
 * @author Amasty Team
 * @copyright Copyright (c) Amasty (https://www.amasty.com)
 * @package Jet Theme Backend for Magento 2 (System)
 */

namespace Amasty\JetTheme\Setup\Patch\Data;

use Amasty\Base\Helper\Deploy;
use Amasty\JetTheme\Setup\AssetManager;
use Amasty\JetTheme\Setup\Operation\CreateCmsBlock;
use Amasty\JetTheme\Setup\Operation\CreateCmsPage;
use Magento\Framework\App\Filesystem\DirectoryList;
use Magento\Framework\Filesystem;
use Magento\Framework\Setup\Patch\DataPatchInterface;
use Magento\Framework\Setup\SchemaSetupInterface;

class InitialInstall implements DataPatchInterface
{
    /**
     * @var Deploy
     */
    private $pubDeployer;

    /**
     * @var CreateCmsBlock
     */
    private $createCmsBlock;

    /**
     * @var CreateCmsPage
     */
    private $createCmsPage;

    /**
     * @var AssetManager
     */
    private $assetManager;

    /**
     * @var Filesystem
     */
    private $filesystem;

    /**
     * @var SchemaSetupInterface
     */
    private $schemaSetup;

    public function __construct(
        Deploy $pubDeployer,
        CreateCmsBlock $createCmsBlock,
        CreateCmsPage $createCmsPage,
        AssetManager $assetManager,
        Filesystem $filesystem,
        SchemaSetupInterface $schemaSetup
    ) {
        $this->pubDeployer = $pubDeployer;
        $this->createCmsBlock = $createCmsBlock;
        $this->createCmsPage = $createCmsPage;
        $this->assetManager = $assetManager;
        $this->filesystem = $filesystem;
        $this->schemaSetup = $schemaSetup;
    }

    /**
     * @return array
     */
    public function getAliases(): array
    {
        return [];
    }

    /**
     * @return string[]
     */
    public static function getDependencies(): array
    {
        return [];
    }

    /**
     * @inerhitDoc
     */
    public function apply(): self
    {
        if (!$this->isJetThemeFolderExist()) {
            $this->pubDeployer->deployFolder(__DIR__ . '/../../../pub');
            $this->assetManager->synchronizeThemeMedia();

            $this->schemaSetup->startSetup();
            $this->createCmsBlock->execute();
            $this->createCmsPage->execute();
            $this->schemaSetup->endSetup();
        }

        return $this;
    }

    /**
     * @return bool
     */
    private function isJetThemeFolderExist(): bool
    {
        try {
            $mediaPath = $this->filesystem->getDirectoryWrite(DirectoryList::MEDIA);

            return $mediaPath->isDirectory('amasty/jet_theme');
        } catch (\Exception $e) {
            return false;
        }
    }
}
