<?php

namespace App\Search;

use App\Search\Action\Command\GetMediaInfoCommand;
use App\Search\Action\Handler\GetMediaInfoHandler;
use App\Search\Action\Result\GetMediaInfoResult;
use stdClass;

class TvEpisodePaginator
{
    /**
     * @var integer
     */
    private $total;

    /**
     * @var integer
     */
    private $lastPage;

    private $items;

    public $limit = 20;

    public $currentPage = 1;

    public function paginate(GetMediaInfoResult $results, int $page = 1, int $limit = 20): static
    {
        $this->total = count($results->media->episodes[$results->season]);
        $this->lastPage = (int) ceil($this->total / $limit);
        $this->items = array_slice($results->media->episodes[$results->season], ($page - 1) * $limit, $limit);
        $this->currentPage = $page;
        $this->limit = $limit;

        return $this;
    }

    public function getTotal(): int
    {
        return $this->total;
    }

    public function getLastPage(): int
    {
        return $this->lastPage;
    }

    public function getItems()
    {
        return $this->items;
    }

    public function getShowing()
    {
        $showingStart = (($this->currentPage - 1) * $this->limit) + 1;
        $showingEnd = (($this->currentPage - 1) * $this->limit) + $this->limit;

        if ($showingEnd > $this->total) {
            $showingEnd = $this->total;
        }

        return sprintf("Showing %d - %d of %d results.", $showingStart, $showingEnd, $this->total);
    }
}
