<?php

namespace idoit\Module\SyneticsJdisc\Graphql\Mutation;

use GraphQL\Mutation;
use GraphQL\Query;
use GraphQL\RawObject;
use GraphQL\Results;
use idoit\Module\SyneticsJdisc\Graphql\AbstractGraphql;
use idoit\Module\SyneticsJdisc\Graphql\ResponseInterface;

// example:
//
// $connector = Connector::instance($serverId);
// $connector->connect();
// $query = new DeleteDevices();
// $query->setDevices([100, 200]);
// $remainingDevices = $connector->query($query);

class DeleteDevices extends AbstractGraphql implements ResponseInterface
{
    private array $devices;

    private string $comment = 'Deleted by i-doit';

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

    /**
     * @param array $devices
     *
     * @return $this
     */
    public function setDevices(array $devices): self
    {
        $this->devices = $devices;
        return $this;
    }

    /**
     * @return string
     */
    public function getFormattedDevices(): string {
        $formattedDevices = [];
        foreach ($this->devices as $device) {
            $formattedDevices[] = "{id: {$device}}";
        }
        return '[' . implode(',', $formattedDevices) . ']';
    }

    /**
     * @param string $comment
     *
     * @return $this
     */
    public function setComment(string $comment): self
    {
        $this->comment = $comment;
        return $this;
    }

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

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


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

    /**
     * @return Query
     */
    public function getQuery(): Query
    {
        return (new Mutation('management'))
            ->setSelectionSet([
                (new Query('devices'))
                    ->setSelectionSet([
                        (new Query('deleteDevices'))
                            ->setArguments([
                                'devices' => new RawObject($this->getFormattedDevices()),
                                'comment' => $this->comment,
                            ])
                            ->setSelectionSet($this->getSelections())
                ])
            ]);
    }
}
