<?php

namespace idoit\Module\JDisc\Graphql\Query;

use GraphQL\Query;
use GraphQL\RawObject;
use GraphQL\Results;
use idoit\Module\JDisc\Graphql\AbstractGraphql;
use idoit\Module\JDisc\Graphql\ResponseInterface;
use idoit\Module\JDisc\Graphql\Type\DeviceInputType;

// example:
//
// $connector = Connector::instance($serverId);
// $connector->connect();
// $query = new IdentifyDevice();
// $query->setParameters([
//     new DeviceInputType(
//         'device',
//         [
//             'type'              => 'Switch',
//             'serialNumber'      => 'abcd',
//             'networkInterfaces' => [
//                 ['physicalAddress' => '00:00:00:00:00:00'],
//             ],
//         ]
//     ),
// ]);
// $connector->query($query);

class IdentifyDevice extends AbstractGraphql implements ResponseInterface
{
    /**
     * @var DeviceInputType
     */
    private ?DeviceInputType $device;

    private array $selections = [
        'id',
        'name',
    ];

    /**
     * @param DeviceInputType $device
     *
     * @return void
     */
    public function setDevice(DeviceInputType $device): void
    {
        $this->device = $device;
    }

    /**
     * @return array
     */
    public function getParameters(): array
    {
        return [];
    }

    /**
     * @return array
     */
    public function getSelections(): array
    {
        return $this->selections;
    }

    /**
     * @param array $selections
     *
     * @return $this
     */
    public function setSelections(array $selections): IdentifyDevice
    {
        $this->selections = $selections;

        return $this;
    }

    /**
     * @param string $selection
     *
     * @return $this
     */
    public function addSelection(string $selection): IdentifyDevice
    {
        $this->selections[] = $selection;

        return $this;
    }

    /**
     * @param Results $results
     *
     * @return array
     */
    public static function getDataFromResults(Results $results): array
    {
        $data = $results->getData();
        return [
            'device' => $data['importing']['devices']['identifyDevice']['foundDevice'] ?: [],
        ];
    }

    /**
     * @return Query
     */
    public function getQuery(): Query
    {
        return (new Query('importing'))
            ->setSelectionSet([
                (new Query('devices'))
                    ->setSelectionSet([
                        (new Query('identifyDevice'))
                            ->setArguments([
                                'device' =>  new RawObject($this->device->getFormattedValue()),
                            ])
                            ->setSelectionSet([
                                (new Query('foundDevice'))
                                    ->setSelectionSet($this->getSelections())
                            ])
                ])
            ]);
    }
}
