<?php
/**
 * @copyright (c) Kufer Software GmbH, Oderstraße 7, D-84453 Mühldorf
 */

namespace Kufer\Web\KuferTools\Utils;

class Blaettern
{
  private $currentPage;
  private $items;
  private $itemsPerPage;

  public function __construct($items, $itemsPerPage, $currentPage = 1)
  {
    $this->items = $items;
    $this->itemsPerPage = $itemsPerPage;
    $this->setCurrentPage($currentPage);
  }

  public function setCurrentPage($page)
  {
    $min = 1;
    $max = $this->getPagesCount();
    if (!is_numeric($page)) {
      $this->currentPage = $min;
    } elseif ($page < $min) {
      $this->currentPage = $min;
    } elseif ($page > $max) {
      $this->currentPage = $max;
    } else {
      $this->currentPage = $page;
    }
  }

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

  public function setToNextPage()
  {
    $this->setCurrentPage($this->currentPage + 1);
  }

  public function setToPreviousPage()
  {
    $this->setCurrentPage($this->currentPage - 1);
  }

  public function getPagesCount()
  {
    if ($this->itemsPerPage == 0) {
      return 1;
    } else {
      $seitenAnzahl = \ceil(count($this->items) / $this->itemsPerPage);

      return max(array($seitenAnzahl, 1));
    }
  }

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

  public function getItemsOnCurrentPage()
  {
    if ($this->itemsPerPage >= count($this->items) || $this->itemsPerPage == 0) {
      return $this->items;
    }

    $start = $this->itemsPerPage * ($this->currentPage - 1);

    return array_slice($this->items, $start, $this->itemsPerPage);
  }

  public function getItemsPerPage()
  {
    return $this->itemsPerPage;
  }

  
  public static function aktualisiereSeiteInSession($toolId, $seiteFromGet, $isEinstieg, $isFilterGeaendert, $sessionPrefix = 'seite_tool')
  {
    if (empty($seiteFromGet)) {
      if (($isEinstieg || $isFilterGeaendert)) {
        \SessionOperations::setVarValueWTIntern($sessionPrefix . $toolId, 1);
      }
    } else {
      \SessionOperations::setVarValueWTIntern($sessionPrefix . $toolId, $seiteFromGet);
    }
  }

  
  public static function getAktuelleSeiteFromSession($toolId, $sessionPrefix = 'seite_tool')
  {
    return \SessionOperations::getVarValueWTIntern($sessionPrefix . $toolId);
  }
}