<?php


namespace Shop\Application\Shopping\ResetOrderState;


use Shop\Models\OrderType\OrderType;
use Shop\Repositories\CustomerOrder\CustomerOrderRepository;
use Shop\Repositories\ProviderOrder\ProviderOrderRepository;

/**
 * Class ResetOrderStateHandler
 * @package Shop\Application\Shopping\ResetOrderState
 */
class ResetOrderStateHandler
{
    protected $customerOrderRepository;
    protected $providerOrderRepository;

    /**
     * ResetOrderStateHandler constructor.
     * @param CustomerOrderRepository $customerOrderRepository
     * @param ProviderOrderRepository $providerOrderRepository
     */
    public function __construct(CustomerOrderRepository $customerOrderRepository,
                                ProviderOrderRepository $providerOrderRepository)
    {
        $this->customerOrderRepository = $customerOrderRepository;
        $this->providerOrderRepository = $providerOrderRepository;
    }

    /**
     * @param ResetOrderStateCommand $command
     */
    public function handle(ResetOrderStateCommand $command): void
    {
        $orderItemEntity = $command->getOrderItemEntity();

        $states = [];

        $order = $orderItemEntity->getOrder();

        foreach ($order->getOrderItems() as $item) {
            $id = $item->getStateId();
            if (!isset($states[$id])) {
                $states[$id] = 1;
            } else {
                $states[$id]++;
            }
        }

        arsort($states);

        $stateId = array_key_first($states);

        if ($stateId && $order->getTypeId() === OrderType::TYPE_CUSTOMER_ORDER) {
            $order->setStateId($stateId);
            $this->customerOrderRepository->save($order);
        } elseif ($order->getTypeId() === OrderType::TYPE_PROVIDER_ORDER) {
            $order->setStateId($stateId);
            $this->providerOrderRepository->save($order);
        }
    }
}