<?php

declare (strict_types=1);
namespace CelerSearch\Vendor\Meilisearch\Endpoints;

use CelerSearch\Vendor\Meilisearch\Contracts\CancelTasksQuery;
use CelerSearch\Vendor\Meilisearch\Contracts\DeleteTasksQuery;
use CelerSearch\Vendor\Meilisearch\Contracts\Endpoint;
use CelerSearch\Vendor\Meilisearch\Contracts\Http;
use CelerSearch\Vendor\Meilisearch\Contracts\Task;
use CelerSearch\Vendor\Meilisearch\Exceptions\TimeOutException;
use function CelerSearch\Vendor\Meilisearch\partial;
/** @internal */
class Tasks extends Endpoint
{
    protected const PATH = '/tasks';
    public function get(int $taskUid) : Task
    {
        return Task::fromArray($this->http->get(self::PATH . '/' . $taskUid), partial(self::waitTask(...), $this->http));
    }
    public function all(array $query = []) : array
    {
        $data = $this->http->get(self::PATH . '/', $query);
        $data['results'] = \array_map(fn(array $task) => Task::fromArray($task, partial(self::waitTask(...), $this->http)), $data['results']);
        return $data;
    }
    public function cancelTasks(?CancelTasksQuery $options) : Task
    {
        $options = $options ?? new CancelTasksQuery();
        return Task::fromArray($this->http->post('/tasks/cancel', null, $options->toArray()), partial(self::waitTask(...), $this->http));
    }
    public function deleteTasks(?DeleteTasksQuery $options) : Task
    {
        $options = $options ?? new DeleteTasksQuery();
        return Task::fromArray($this->http->delete(self::PATH, $options->toArray()), partial(self::waitTask(...), $this->http));
    }
    /**
     * @internal
     *
     * @throws TimeOutException
     */
    public static function waitTask(Http $http, int $taskUid, int $timeoutInMs, int $intervalInMs) : Task
    {
        $timeoutTemp = 0;
        while ($timeoutInMs > $timeoutTemp) {
            $task = Task::fromArray($http->get(self::PATH . '/' . $taskUid), partial(self::waitTask(...), $http));
            if ($task->isFinished()) {
                return $task;
            }
            $timeoutTemp += $intervalInMs;
            \usleep(1000 * $intervalInMs);
        }
        throw new TimeOutException();
    }
}
