<?php
// Copyright (c) Pickware GmbH. All rights reserved.
// This file is part of software that is released under a proprietary license.
// You must not copy, modify, distribute, make publicly available, or execute
// its contents or parts thereof without express permission by the copyright
// holder, unless otherwise permitted by law.

namespace Shopware\Plugins\ViisonCommon\Classes\Installation\ArticleAttributeElement;

use Doctrine\ORM\EntityManager;
use Shopware\Plugins\ViisonCommon\Classes\Installation\AttributeConfiguration\UninstallationHelper as ConfigUninstallationHelper;

class UninstallationHelper
{
    /**
     * @var EntityManager
     */
    private $entityManager;

    /**
     * @param EntityManager $entityManager
     */
    public function __construct(EntityManager $entityManager)
    {
        $this->entityManager = $entityManager;
    }

    /**
     * Removes article attribute configuration fields (from the backend view).
     *
     * Remark: This method can be used for the configuration fields in SW < 5.2 and calls
     * ViisonCommon\Classes\Installation\AttributeConfiguration\UninstallationHelper if called from SW >= 5.2.
     *
     * @param array $elementNames
     */
    public function removeArticleAttributeElementsIfExist(array $elementNames)
    {
        if (!class_exists('Shopware\\Models\\Attribute\\Configuration')) {
            // Handle Shopware < 5.2:
            $this->removeArticleAttributeElementsIfExistLegacy($elementNames);

            return;
        }

        // Handle Shopware >= 5.2:
        $columnNames = array_map(function ($name) {
            return ConfigurationHelper::transformToColumnName($name);
        }, $elementNames);
        $configurationNameMap = [
            's_articles_attributes' => $columnNames,
        ];

        $articleConfigurationHelper = new ConfigUninstallationHelper($this->entityManager);
        $articleConfigurationHelper->removeAttributeConfigurationsIfExist($configurationNameMap);
    }

    /**
     * Removes article attribute configuration fields (from the backend view) for SW < 5.2
     *
     * @param array $elementNames
     */
    private function removeArticleAttributeElementsIfExistLegacy(array $elementNames)
    {
        foreach ($elementNames as $elementName) {
            $articleElement = $this->entityManager->getRepository('Shopware\\Models\\Article\\Element')->findOneBy([
                'name' => $elementName,
            ]);
            if ($articleElement) {
                $this->entityManager->remove($articleElement);
            }
        }
        $this->entityManager->flush();
    }
}
