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

use Shopware\Models\Config\Element;
use Shopware\Models\Config\Form;
use Shopware\Components\Model\ModelManager;

/**
 * Service to handle hidden config fields.
 *
 * Hidden config fields can be used to save state for the plugin, that should not be visible to the user, e.g. a
 * migration state.
 */
class HiddenConfigStorageService
{
    /**
     * @var ModelManager
     */
    private $entityManager;

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

    /**
     * Set a hidden config value.
     *
     * @param string $name
     * @param string $type
     * @param mixed $value
     */
    public function setConfigValue($name, $type, $value)
    {
        // Check for a saved default grid label template
        $configValue = $this->entityManager->getRepository('Shopware\\Models\\Config\\Element')->findOneBy([
            'name' => $name,
        ]);

        if (!$configValue) {
            // Create new config element using a fake form, since all elements must belong to a form
            $configValue = new Element($type, $name, []);
            /** @var Form $fakeForm */
            $fakeForm = $this->entityManager->getPartialReference('Shopware\\Models\\Config\\Form', 0);
            $configValue->setForm($fakeForm);
            $this->entityManager->persist($configValue);
        }

        // Save the value
        $configValue->setValue($value);
        $this->entityManager->flush($configValue);
    }

    /**
     * Returns the current hidden config value.
     *
     * @param string $name
     * @return mixed
     */
    public function getConfigValue($name)
    {
        $configValue = $this->entityManager->getRepository('Shopware\\Models\\Config\\Element')->findOneBy([
            'name' => $name,
        ]);

        return ($configValue) ? $configValue->getValue() : null;
    }

    /**
     * Clears a config value.
     *
     * @param string $name
     */
    public function removeConfigValue($name)
    {
        $configValue = $this->entityManager->getRepository('Shopware\\Models\\Config\\Element')->findOneBy([
            'name' => $name,
        ]);

        if ($configValue) {
            $this->entityManager->remove($configValue);
            $this->entityManager->flush($configValue);
        }
    }
}
