<?php

namespace KupShop\AutomationConfiguratorBundle\Configurator\Orders\Conditions\Fields;

use KupShop\AutomationConfiguratorBundle\Configurator\Interfaces\Conditions\Fields\Field;
use KupShop\AutomationConfiguratorBundle\Configurator\Orders\OrdersContext;
use KupShop\AutomationConfiguratorBundle\Util\ExpressionContext;

class DurationFromOrderHandled extends Field implements OrdersContext
{
    public function getConfig(): array
    {
        return [
            'label' => 'Čas od vyřízení objednávky',
            'type' => 'duration',
            'function' => true,
        ];
    }

    public function getName(): string
    {
        return 'duration_from_order_handled';
    }

    public function getGroupName(): ?string
    {
        return 'time';
    }

    public function getCompareValue(ExpressionContext $context, $args = null)
    {
        $context = $context->getContext();
        $orderDateTime = new \DateTime($context['o_date_handle']);
        [$diff, $diffAnchor] = $this->fieldsUtil->substractTimeFromNowGetWithAnchor($args[0], $args[1], $args[2], $args[3] ?? false);

        return $this->fieldsUtil->getDurationCompareCondition($orderDateTime, $diff, $diffAnchor, $args[4] ?? 'greater');
    }

    public function modifyPrefetchFastCondition($context, $jsonValue)
    {
        $params = $this->prefetchUtil->getDateIntervalValues($jsonValue);

        [$diff, $diffAnchor] = $this->fieldsUtil->substractTimeFromNowGetWithAnchor($params['days'], $params['hours'], $params['seconds'], $params['onlyWorkDays']);

        switch ($params['operator']) {
            case 'less':
                $context->andWhere('o.date_handle IS NOT NULL && o.date_handle > :afterHandled');
                break;
            default: // greater
                $context->andWhere('o.date_handle IS NOT NULL && o.date_handle < :afterHandled AND o.date_handle > :beforeHandled');
        }

        $context->addParameters([
            'afterHandled' => $diff->format('Y-m-d H:i:s'),
            'beforeHandled' => $diffAnchor->format('Y-m-d H:i:s'),
        ]);

        return $context;
    }
}
