<?php

namespace AsyncAws\Athena\Result;

use AsyncAws\Athena\AthenaClient;
use AsyncAws\Athena\Input\ListTableMetadataInput;
use AsyncAws\Athena\ValueObject\Column;
use AsyncAws\Athena\ValueObject\TableMetadata;
use AsyncAws\Core\Exception\InvalidArgument;
use AsyncAws\Core\Response;
use AsyncAws\Core\Result;

/**
 * @implements \IteratorAggregate<TableMetadata>
 */
class ListTableMetadataOutput extends Result implements \IteratorAggregate
{
    /**
     * A list of table metadata.
     *
     * @var TableMetadata[]
     */
    private $tableMetadataList;

    /**
     * A token generated by the Athena service that specifies where to continue pagination if a previous request was
     * truncated. To obtain the next set of pages, pass in the NextToken from the response object of the previous page call.
     *
     * @var string|null
     */
    private $nextToken;

    /**
     * Iterates over TableMetadataList.
     *
     * @return \Traversable<TableMetadata>
     */
    public function getIterator(): \Traversable
    {
        yield from $this->getTableMetadataList();
    }

    public function getNextToken(): ?string
    {
        $this->initialize();

        return $this->nextToken;
    }

    /**
     * @param bool $currentPageOnly When true, iterates over items of the current page. Otherwise also fetch items in the next pages.
     *
     * @return iterable<TableMetadata>
     */
    public function getTableMetadataList(bool $currentPageOnly = false): iterable
    {
        if ($currentPageOnly) {
            $this->initialize();
            yield from $this->tableMetadataList;

            return;
        }

        $client = $this->awsClient;
        if (!$client instanceof AthenaClient) {
            throw new InvalidArgument('missing client injected in paginated result');
        }
        if (!$this->input instanceof ListTableMetadataInput) {
            throw new InvalidArgument('missing last request injected in paginated result');
        }
        $input = clone $this->input;
        $page = $this;
        while (true) {
            $page->initialize();
            if (null !== $page->nextToken) {
                $input->setNextToken($page->nextToken);

                $this->registerPrefetch($nextPage = $client->listTableMetadata($input));
            } else {
                $nextPage = null;
            }

            yield from $page->tableMetadataList;

            if (null === $nextPage) {
                break;
            }

            $this->unregisterPrefetch($nextPage);
            $page = $nextPage;
        }
    }

    protected function populateResult(Response $response): void
    {
        $data = $response->toArray();

        $this->tableMetadataList = empty($data['TableMetadataList']) ? [] : $this->populateResultTableMetadataList($data['TableMetadataList']);
        $this->nextToken = isset($data['NextToken']) ? (string) $data['NextToken'] : null;
    }

    private function populateResultColumn(array $json): Column
    {
        return new Column([
            'Name' => (string) $json['Name'],
            'Type' => isset($json['Type']) ? (string) $json['Type'] : null,
            'Comment' => isset($json['Comment']) ? (string) $json['Comment'] : null,
        ]);
    }

    /**
     * @return Column[]
     */
    private function populateResultColumnList(array $json): array
    {
        $items = [];
        foreach ($json as $item) {
            $items[] = $this->populateResultColumn($item);
        }

        return $items;
    }

    /**
     * @return array<string, string>
     */
    private function populateResultParametersMap(array $json): array
    {
        $items = [];
        foreach ($json as $name => $value) {
            $items[(string) $name] = (string) $value;
        }

        return $items;
    }

    private function populateResultTableMetadata(array $json): TableMetadata
    {
        return new TableMetadata([
            'Name' => (string) $json['Name'],
            'CreateTime' => (isset($json['CreateTime']) && ($d = \DateTimeImmutable::createFromFormat('U.u', \sprintf('%.6F', $json['CreateTime'])))) ? $d : null,
            'LastAccessTime' => (isset($json['LastAccessTime']) && ($d = \DateTimeImmutable::createFromFormat('U.u', \sprintf('%.6F', $json['LastAccessTime'])))) ? $d : null,
            'TableType' => isset($json['TableType']) ? (string) $json['TableType'] : null,
            'Columns' => !isset($json['Columns']) ? null : $this->populateResultColumnList($json['Columns']),
            'PartitionKeys' => !isset($json['PartitionKeys']) ? null : $this->populateResultColumnList($json['PartitionKeys']),
            'Parameters' => !isset($json['Parameters']) ? null : $this->populateResultParametersMap($json['Parameters']),
        ]);
    }

    /**
     * @return TableMetadata[]
     */
    private function populateResultTableMetadataList(array $json): array
    {
        $items = [];
        foreach ($json as $item) {
            $items[] = $this->populateResultTableMetadata($item);
        }

        return $items;
    }
}
