<?php

declare(strict_types=1);

namespace Plugin\tnt_stabila_shop\src\Abstracts;

use Plugin\tnt_stabila_shop\src\Repositories\DatabaseRepository;

abstract class AbstractPaginatedData
{
    protected int $totalPages  = 1;
    protected int $currentPage = 1;

    public function __construct(protected DatabaseRepository $database)
    {
    }

    public function getPreviousPage(): int
    {
        return $this->currentPage === 1
            ? 1
            : $this->currentPage - 1;
    }

    public function getCurrentPage(): int
    {
        return $this->currentPage;
    }

    public function getNextPage(): int
    {
        return $this->currentPage === $this->totalPages
            ? $this->totalPages
            : $this->currentPage + 1;
    }

    /**
     * @return object{offset: int, active: bool, threeDots: bool}[]
     */
    public function getPages(): array
    {
        $result    = [];
        $offsets[] = 1;
        $offsets[] = $this->currentPage - 2;
        $offsets[] = $this->currentPage - 1;
        $offsets[] = $this->currentPage;
        $offsets[] = $this->currentPage + 1;
        $offsets[] = $this->currentPage + 2;
        $offsets[] = $this->totalPages;
        if ($offsets[0] === $this->currentPage) {
            unset($offsets[0]);
        }
        if ($offsets[1] <= 1) {
            unset($offsets[1]);
        }
        if ($offsets[2] <= 1) {
            unset($offsets[2]);
        }
        if ($offsets[4] >= $this->totalPages) {
            unset($offsets[4]);
        }
        if ($offsets[5] >= $this->totalPages) {
            unset($offsets[5]);
        }
        if ($this->currentPage === $this->totalPages) {
            unset($offsets[6]);
        }
        $offsets    = \array_values($offsets);
        $lastOffset = 0;
        foreach ($offsets as $offset) {
            if (($offset - 1) !== $lastOffset) {
                $result[] = (object)[
                    'offset'    => 0,
                    'active'    => false,
                    'threeDots' => true,
                ];
            }
            $result[]   = (object)[
                'offset'    => $offset,
                'active'    => $offset === $this->currentPage,
                'threeDots' => false,
            ];
            $lastOffset = $offset;
        }

        return $result;
    }

    public function getPageSize(): int
    {
        return \count($this->getData());
    }

    /**
     * @return array<mixed>
     */
    abstract public function getData(string $search = ''): array;
}
