<?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 StartJobs();
// $query->setJobs([2, 3]);
// $jobsStatuses = $connector->query($query);

class StartJobs extends AbstractGraphql implements ResponseInterface
{
    private array $jobs;

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

    /**
     * @return string
     */
    public function getFormattedJobs(): string {
        $formattedJobs = [];
        foreach ($this->jobs as $job) {
            $formattedJobs[] = "{jobId: {$job}}";
        }
        return '[' . implode(',', $formattedJobs) . ']';
    }

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

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

    /**
     * @param Results $results
     *
     * @return array
     */
    public static function getDataFromResults(Results $results): array
    {
        $data = $results->getData();
        return  [
            'status' => $data['discovery']['control']['startJobs'],
        ];
    }

    /**
     * @return Query
     */
    public function getQuery(): Query
    {
        return (new Mutation('discovery'))
            ->setSelectionSet([
                (new Query('control'))
                    ->setSelectionSet([
                        (new Query('startJobs'))
                            ->setArguments([
                                'discoveryJobReferences' => new RawObject($this->getFormattedJobs()),
                            ])
                ])
            ]);
    }
}
