<?php declare(strict_types=1);

namespace zenit\PlatformAtmosSet2;

use Shopware\Core\Framework\Context;
use Shopware\Core\Framework\DataAbstractionLayer\EntityRepository;
use Shopware\Core\Framework\DataAbstractionLayer\Search\Criteria;
use Shopware\Core\Framework\DataAbstractionLayer\Search\Filter\EqualsFilter;
use Shopware\Core\Framework\Plugin\Context\UpdateContext;
use Shopware\Storefront\Framework\ThemeInterface;
use Shopware\Core\Framework\Plugin;

class zenitPlatformAtmosSet2 extends Plugin implements ThemeInterface
{
    /**
     * @var Context
     */
    private $context;

    public function getThemeConfigPath(): string
    {
        return 'theme.json';
    }

    public function postUpdate(UpdateContext $updateContext): void
    {
        parent::postUpdate($updateContext);

        $this->updateThemeDuplicates();
    }

    private function updateThemeDuplicates(): void
    {
        $this->context = Context::createDefaultContext();

        $criteriaTheme = new Criteria();
        $criteriaTheme->addFilter(new EqualsFilter('technicalName', 'zenitPlatformAtmosSet2'));

        /** @var EntityRepository $themeRepo */
        $themeRepo = $this->container->get('theme.repository');
        $parentTheme = $themeRepo->search($criteriaTheme, $this->context)->first();

        if (!$parentTheme) {
            return;
        }

        $criteriaThemeDuplicates = new Criteria();
        $criteriaThemeDuplicates->addFilter(new EqualsFilter('parentThemeId', $parentTheme->get('id')));

        $resultThemeDuplicates = $themeRepo->search($criteriaThemeDuplicates, $this->context)->getElements();

        if (!$resultThemeDuplicates) {
            return;
        }

        foreach ($resultThemeDuplicates as $themeDuplicate) {

            $data = [
                'id' => $themeDuplicate->get('id'),
                'baseConfig' => $parentTheme->get('baseConfig')
            ];

            if (!$themeDuplicate->get('previewMediaId')) {
                $data['previewMediaId'] = $parentTheme->get('previewMediaId');
            }

            $themeRepo->update([$data], $this->context);
        }
    }
}
