<?php

namespace common\components;

use common\logic\Producer\Producer\Model\Producer;
use yii\base\ErrorException;

class BusinessLogic
{
    use BusinessLogicTrait;

    public function getContainers()
    {
        return [
            $this->getTaxRateContainer(),
            $this->getUserUserGroupContainer(),
            $this->getUserGroupContainer(),
            $this->getCreditHistoryContainer(),
            $this->getProducerPriceRangeContainer(),
            $this->getUserProducerContainer(),
            $this->getUserContainer(),
            $this->getOrderSatusHistoryContainer(),
            $this->getPointSaleDistributionContainer(),
            $this->getProductDistributionContainer(),
            $this->getProductCategoryContainer(),
            $this->getProductPointSaleContainer(),
            $this->getProductOrderContainer(),
            $this->getProductPriceContainer(),
            $this->getProductSubscriptionContainer(),
            $this->getUserPointSaleContainer(),
            $this->getQuotationContainer(),
            $this->getInvoiceContainer(),
            $this->getDeliveryNoteContainer(),
            $this->getDocumentContainer(),
            $this->getPointSaleContainer(),
            $this->getSubscriptionContainer(),
            $this->getProductContainer(),
            $this->getDistributionContainer(),
            $this->getProducerContainer(),
            $this->getOrderContainer(),
        ];
    }

    public function setProducerContext(Producer $producer)
    {
        foreach($this->getContainers() as $container) {
            foreach($container->getServices() as $serviceClass) {
                $instanceService = $serviceClass::getInstance();
                $instanceService->setProducerContext($producer);
            }
        }
    }

    /*
     * Hiérarchie des apps
     */

    public function getContainerLevelHierarchyByService($serviceClass): int
    {
        $containersArray = $this->getContainers();
        $entityFqcnService = $this->getEntityFqcnByService($serviceClass);

        foreach($containersArray as $key => $container) {
            if($container->getEntityFqcn() == $entityFqcnService) {
                return $key;
            }
        }
    }

    public function getEntityFqcnByService(string $serviceClass): string
    {
        $containersArray = $this->getContainers();

        foreach($containersArray as $container) {
            if(in_array($serviceClass, $container->getServices())) {
                return $container->getEntityFqcn();
            }
        }

        throw new ErrorException('Service '.$serviceClass.' introuvable dans les containers.');
    }
}