<?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\AttributeConfiguration;

use Doctrine\ORM\EntityManager;

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

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

    /**
     * Checks whether a Shopware\Models\Attribute\Configuration with the given $tableName and $columnName
     * exists and, in case it doesn't, creates a new Shopware\Models\Attribute\Configuration instance.
     * Finally the new/existing configuration is updated with the given values and saved in the database.
     * Remark: If called in a Shopware environment < 5.2, this method does nothing, since the attribute
     * configuration is not yet available.
     *
     * @param string $tableName
     * @param string $columnName
     * @param string $type
     * @param string $label
     * @param string $helpText
     * @param int $position (optional)
     * @param string $entity (optional)
     */
    public function createAttributeConfigurationUnlessExists($tableName, $columnName, $type, $label, $helpText, $position = 0, $entity = null, $supportText = '')
    {
        if (!class_exists('Shopware\\Models\\Attribute\\Configuration')) {
            return;
        }

        // Check for existing configuration
        $configuration = $this->entityManager->getRepository('Shopware\\Models\\Attribute\\Configuration')->findOneBy([
            'tableName' => $tableName,
            'columnName' => $columnName,
        ]);
        if (!$configuration) {
            // Create a new configuration
            $configuration = new \Shopware\Models\Attribute\Configuration();
            $configuration->setTableName($tableName);
            $configuration->setColumnName($columnName);
        }

        // Update the configuration
        $configuration->setColumnType($type);
        $configuration->setLabel($label);
        $configuration->setHelpText($helpText);
        $configuration->setPosition($position);
        $configuration->setEntity($entity);
        $configuration->setSupportText($supportText);
        $configuration->setDisplayInBackend(true);
        $configuration->setCustom(false);

        // Save configuration
        $this->entityManager->persist($configuration);
        $this->entityManager->flush($configuration);
    }
}
