<?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\SubApplicationLoading\SubApplicationBuilder;

use BadMethodCallException;
use Shopware\Plugins\ViisonCommon\Components\SubApplicationLoading\SubApplication;
use Shopware\Plugins\ViisonCommon\Components\SubApplicationLoading\SubApplicationCodeGenerator\SubApplicationCodeGeneratorFactoryService;
use Shopware\Plugins\ViisonCommon\Components\SubApplicationLoading\SubApplicationRegistry;

/**
 * Builder to create a SubApplications that contains model extension for another SubApplication.
 *
 * This class is a wrapper providing a fluent API for the SubApplication configuration.
 */
class ModelExtensionBuilder extends AbstractSubApplicationBuilder
{
    use SubApplicationExtending;
    use SubApplicationDependent;

    /**
     * @inheritdoc
     */
    public function registerInSubApplicationRegistry(
        SubApplicationRegistry $subApplicationRegistry,
        SubApplicationCodeGeneratorFactoryService $subApplicationCodeGeneratorFactory
    ) {
        if (empty($this->nameOfExtendedSubApplication)) {
            throw new BadMethodCallException(
                'A ModelExtension must extend a SubApplication. ' .
                'Did you forget to call extendingSubApplication()?'
            );
        }

        $codeGenerator = $subApplicationCodeGeneratorFactory->createPlainSubApplicationCodeGenerator(
            $this->name,
            $this->pluginPath,
            $this->controllerClassName
        );
        $subApplication = new SubApplication($this->name, $codeGenerator);
        $subApplication->addDependencyNames($this->namesOfRequiredSubApplications);
        $subApplicationRegistry->registerSubApplicationAsDependency(
            $subApplication,
            $this->nameOfExtendedSubApplication
        );
    }
}
