<?php declare(strict_types=1);

namespace kwh\KWHnext;

use Shopware\Core\Framework\DataAbstractionLayer\Search\Criteria;
use Shopware\Core\Framework\DataAbstractionLayer\Search\Filter\EqualsFilter;
use Shopware\Core\Framework\Plugin;
use Shopware\Core\Framework\Plugin\Context\InstallContext;
use Shopware\Core\Framework\Plugin\Context\UninstallContext;
use Shopware\Core\Framework\Plugin\Context\UpdateContext;
use Shopware\Core\System\CustomField\Aggregate\CustomFieldSet\CustomFieldSetEntity;
use Shopware\Core\System\CustomField\CustomFieldEntity;
use Shopware\Core\System\CustomField\CustomFieldTypes;
use Shopware\Storefront\Framework\ThemeInterface;

class KWHnextTheme extends Plugin implements ThemeInterface

{
    public const CUSTOM_FIELD_PREFIX = 'kwhnext_category_tree_teaser';
    
    public function getThemeConfigPath(): string
    {
        return 'theme.json';
    }
    
    public function install(InstallContext $installContext): void
    {
        $this->createCustomFieldSystem($installContext);
        parent::install($installContext);
    }
    
    public function uninstall(UninstallContext $uninstallContext): void
    {
        $this->removeCustomFieldSystem($uninstallContext);
        parent::uninstall($uninstallContext);
    }
    
    public function update(UpdateContext $updateContext): void
    {
        $this->updateCustomFieldSystem($updateContext);
        parent::update($updateContext);
    }
    
    
    private function createCustomFieldSystem(InstallContext $installContext)
    {
        $customFieldSetRepository = $this->container->get('custom_field_set.repository');
        $context = $installContext->getContext();
        
        //check if the custom field set is defined
        $criteria = new Criteria();
        $criteria->addFilter(new EqualsFilter('name', static::CUSTOM_FIELD_PREFIX));
        $customFieldSetEntity = $customFieldSetRepository->searchIds($criteria, $context);
        if (!$customFieldSetEntity->getTotal()) {
            $customFieldSetRepository->create(
                [
                    [
                        'name' => static::CUSTOM_FIELD_PREFIX,
                        'customFields' => $this->_getCustomFieldItems(),
                        'relations' => [
                            ['entityName' => 'category']
                        ],
                        'config' => [
                            'label' => [
                                'en-GB' => 'KWHnext',
                                'de-DE' => 'KWHnext'
                            ],
                            'translated' => true
                        ]
                    ]
                ],
                $context
            );
        }
    }
    
    private function updateCustomFieldSystem(UpdateContext $updateContext)
    {
        $customFieldSetRepository = $this->container->get('custom_field_set.repository');
        $context = $updateContext->getContext();
        
        //check if the custom field set is defined
        $criteria = new Criteria();
        $criteria->addFilter(new EqualsFilter('name', static::CUSTOM_FIELD_PREFIX));
        $criteria->addAssociation('customFields');
        /** @var CustomFieldSetEntity $customFieldSetEntity */
        $customFieldSetEntity = $customFieldSetRepository->search($criteria, $context)->first();
        if ($customFieldSetEntity) {
            
            $customFields = $this->_getCustomFieldItems();
            
            /** @var CustomFieldEntity $item */
            foreach ($customFieldSetEntity->getCustomFields() as $item) {
                $key = array_search($item->getName(), array_column($customFields, 'name'));
                if ($key !== FALSE) {
                    $customFields[$key]['id'] = $item->getId();
                }
            }
            
            $customFieldSetRepository->upsert(
                [
                    [
                        'id' => $customFieldSetEntity->getId(),
                        'name' => static::CUSTOM_FIELD_PREFIX,
                        'customFields' => $customFields
                    ]
                ],
                $context
            );
        }
    }
    
    private function removeCustomFieldSystem(UninstallContext $uninstallContext)
    {
        $customFieldSetRepository = $this->container->get('custom_field_set.repository');
        $context = $uninstallContext->getContext();
        
        //check if the custom field set is defined
        $criteria = new Criteria();
        $criteria->addFilter(new EqualsFilter('name', static::CUSTOM_FIELD_PREFIX));
        $customFieldSetEntity = $customFieldSetRepository->searchIds($criteria, $context);
        
        if ($customFieldSetEntity->getTotal() && !$uninstallContext->keepUserData()) {
            $customFieldSetRepository->delete(array_values($customFieldSetEntity->getData()), $context);
        }
    }
    
    private function _getCustomFieldItems(): array
    {
        
        return [
            [
                'name' => static::CUSTOM_FIELD_PREFIX . '_number',
                'type' => CustomFieldTypes::TEXT,
                'config' => [
                    'type' => 'text',
                    'label' => [
                        'en-GB' => 'KWH Catalog Chapternumber',
                        'de-DE' => 'KWH Katalog Kapitelnummer'
                    ],
                    'componentName' => 'sw-field',
                    'customFieldType' => 'text',
                    'helpText' => [
                        'en-GB' => 'number according to the printed catalogue, displays in frontend before cat title',
                        'de-DE' => 'Entsprechende Nummer im Printkatalog, wird vor dem Kategorietitel dargestellt'
                    ],
                    'translated' => false
                ]
            ],
            [
                'name' => static::CUSTOM_FIELD_PREFIX . '_bannerimg',
                'type' => CustomFieldTypes::MEDIA,
                'config' => [
                    'type' => 'media',
                    'label' => [
                        'en-GB' => 'Bannerimage',
                        'de-DE' => 'Bannerbild für Kategorieseiten'
                    ],
                    'componentName' => 'sw-media-field',
                    'customFieldType' => 'media',
                    'helpText' => [
                        'en-GB' => '',
                        'de-DE' => 'Querformat 1920 × 300px, kann für Header verwendet werden'
                    ],
                    'translated' => false
                ]
            
            ],
            [
                'name' => static::CUSTOM_FIELD_PREFIX . '_icon',
                'type' => CustomFieldTypes::MEDIA,
                'config' => [
                    'type' => 'media',
                    'label' => [
                        'en-GB' => 'Icon',
                        'de-DE' => 'Icon'
                    ],
                    'componentName' => 'sw-media-field',
                    'customFieldType' => 'media',
                    'helpText' => [
                        'en-GB' => '',
                        'de-DE' => ''
                    ],
                    'translated' => false
                ]
            
            ]
        
        
        ];
    }
    
}
