<?php

declare(strict_types=1);

namespace KupShop\ReturnsBundle\Deliveries\Utils;

use KupShop\KupShopBundle\Util\Entity\EntityUtil;
use KupShop\ReturnsBundle\Entity\ReturnDeliveryEntity;
use KupShop\ReturnsBundle\Translations\ReturnDeliveryTranslation;
use Symfony\Component\DependencyInjection\ServiceLocator;

class ReturnDeliveries
{
    protected ServiceLocator $serviceLocator;
    protected EntityUtil $entityUtil;

    protected $deliveries;

    protected $returnDeliveriesEntityCache;

    public function __construct(ServiceLocator $serviceLocator)
    {
        $this->serviceLocator = $serviceLocator;
    }

    public function getAllDeliveryTypes(): array
    {
        if (!$this->deliveries) {
            foreach ($this->serviceLocator->getProvidedServices() as $id => $service) {
                /**
                 * @var ReturnDelivery $delivery
                 */
                $delivery = $this->serviceLocator->get($id);
                if ($delivery->isEnabled()) {
                    $this->deliveries[$delivery->getClassName()] = $delivery;
                }
            }
        }

        return $this->deliveries;
    }

    public function getDeliveryType($type): ReturnDelivery
    {
        $deliveryTypes = $this->getAllDeliveryTypes();

        return $deliveryTypes[$type];
    }

    /**
     * @return ReturnDeliveryEntity[]
     */
    public function getReturnDeliveryEntities(): array
    {
        if (empty($this->returnDeliveriesEntityCache)) {
            $returnDeliveries = sqlQueryBuilder()->select('rd.*')->from('return_delivery', 'rd')
                ->andWhere(\Query\Translation::coalesceTranslatedFields(ReturnDeliveryTranslation::class))
                ->orderBy('position')
                ->execute()->fetchAllAssociative();

            $returnDeliveriesEntity = [];
            foreach ($returnDeliveries as $returnDeliveryRow) {
                $returnDeliveriesEntity[$returnDeliveryRow['id']] = $this->entityUtil->createEntity($returnDeliveryRow,
                    ReturnDeliveryEntity::class);
            }

            $this->returnDeliveriesEntityCache = $returnDeliveriesEntity;
        }

        return $this->returnDeliveriesEntityCache;
    }

    public function getReturnDeliveryEntity(?int $id): ?ReturnDeliveryEntity
    {
        $allEntities = $this->getReturnDeliveryEntities();

        return $allEntities[$id] ?? null;
    }

    /**
     * @required
     */
    public function setEntityUtil(EntityUtil $entityUtil): void
    {
        $this->entityUtil = $entityUtil;
    }
}
