<?php

namespace KupShop\OrderDiscountBundle\Triggers;

use KupShop\KupShopBundle\Context\UserContext;
use KupShop\KupShopBundle\Query\JsonOperator;
use KupShop\OrderingBundle\Entity\Purchase\PurchaseState;
use Query\Operator;

class UserTrigger extends AbstractTrigger
{
    protected static $type = 'user_users';
    protected static $position = 63;
    protected $adminTemplate = 'triggers/user_users.tpl';

    /** @var UserContext */
    private $userContext;

    /**
     * @return $this
     *
     * @required
     */
    public function setUserContext(UserContext $userContext)
    {
        $this->userContext = $userContext;

        return $this;
    }

    public function getDiscountFilterSpec(PurchaseState $purchaseState)
    {
        return Operator::andX(
            Operator::equals(['odt.type' => static::getType()]),
            Operator::orX(
                Operator::andX(
                    JsonOperator::contains('odt.data', 'users', $this->userContext->getActiveId()),
                    JsonOperator::contains('odt.data', 'users_invert', 'invert')
                ),
                Operator::andX(
                    Operator::not(JsonOperator::contains('odt.data', 'users', $this->userContext->getActiveId())),
                    Operator::not(JsonOperator::contains('odt.data', 'users_invert', 'invert'))
                )
            )
        );
    }

    /**
     * @return bool
     *
     * @throws \Exception
     */
    public function checkValidity(&$data)
    {
        if (!empty($data['users'])) {
            return true;
        }

        throw new \Exception($this->getName().' ['.$this->getType().'] - data is not valid.');
    }

    public function handleData($data)
    {
        $data['users'] = array_map('intval', $data['users'] ?? []);

        return $data;
    }
}
