<?php
// Copyright (c) Pickware GmbH. All rights reserved.
// This file is part of software that is released under a proprietary license.
// You must not copy, modify, distribute, make publicly available, or execute
// its contents or parts thereof without express permission by the copyright
// holder, unless otherwise permitted by law.

namespace Shopware\Plugins\ViisonPickwareMobile\Components\QueryComponentArrayCoding;

use Shopware\Plugins\ViisonPickwareMobile\Components\QueryBuilder\ComparisonQueryComponent;
use Shopware\Plugins\ViisonPickwareMobile\Components\QueryBuilder\QueryComponent;

class ComparisonQueryComponentArrayCoder implements QueryComponentArrayCoder
{
    use ArrayDecoding;

    const CODABLE_TYPE = 'comparison';

    /**
     * @inheritdoc
     */
    public function getCodableType()
    {
        return self::CODABLE_TYPE;
    }

    /**
     * @inheritdoc
     */
    public function canEncodeQueryComponent(QueryComponent $queryComponent)
    {
        return $queryComponent instanceof ComparisonQueryComponent;
    }

    /**
     * @inheritdoc
     */
    public function encodeToArray(QueryComponent $queryComponent, callable $encodeChildComponent)
    {
        return [
            'type' => $this->getCodableType(),
            'leftOperand' => $encodeChildComponent($queryComponent->getLeftOperand()),
            'operator' => $queryComponent->getOperator(),
            'rightOperand' => $encodeChildComponent($queryComponent->getRightOperand()),
        ];
    }

    /**
     * @inheritdoc
     */
    public function decodeFromArray(array $encodedQueryComponent, callable $decodeChildComponent)
    {
        $this->assertCodableType($encodedQueryComponent);
        $this->assertFieldExists($encodedQueryComponent, 'leftOperand');
        $this->assertFieldExists($encodedQueryComponent, 'operator');
        $this->assertFieldExists($encodedQueryComponent, 'rightOperand');

        return new ComparisonQueryComponent(
            $decodeChildComponent($encodedQueryComponent['leftOperand']),
            $encodedQueryComponent['operator'],
            $decodeChildComponent($encodedQueryComponent['rightOperand'])
        );
    }
}
