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

use Doctrine\ORM\EntityManager;

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

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

    /**
     * Removes all Shopware\Models\Media\Album entities as well as their associated entity
     * Shopware\Models\Media\Settings, whose name matches one of the given names.
     *
     * @param array $names
     */
    public function removeMediaAlbumsIfExist(array $names)
    {
        foreach ($names as $name) {
            // Try to find the album
            $album = $this->entityManager->getRepository('Shopware\\Models\\Media\\Album')->findOneBy([
                'name' => $name,
            ]);
            if ($album) {
                // Remove the album and its settings
                $this->entityManager->remove($album);
                $this->entityManager->remove($album->getSettings());
            }
        }

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