<?php
/**
 * @copyright (c) Kufer Software GmbH, Loisachstrasse 4, D-84453 Mühldorf
 */

namespace Kufer\Web\Classes\Rss;

abstract class RssFeed
{
  private const TMPDIR = BASEDIR . 'webbasys/tmp/';
  private $cacheFile;
  private $cachePudateFile;
  private $arrayPubDate = array();
  private $arrayPubDateNeeded = array();

  public function __construct()
  {
    $this->cacheFile = self::TMPDIR . 'rss-' . $this->getFeedname() . '.cache';
    $this->cachePudateFile = self::TMPDIR . 'rss-' . $this->getFeedname() . '.pubdate.cache';
  }

  
  
  abstract protected function getRssItems(\KursWebUebersichtSettings $pSettings): array;

  
  abstract public static function getFeedname(): string;

  protected function useCache(): bool
  {
    return true;
  }

  public function loadPubDates(): void
  {
    if (!file_exists(self::TMPDIR)) {
      mkdir(self::TMPDIR);
    }
    $this->arrayPubDate = $this->createPubDateArray();
  }

  
  public function getRss(bool $pClearCache = false): string
  {
    $this->loadPubDates();
    if ($this->useCache() && $this->isCached() && !$pClearCache) {
      return $this->getCachedContent();
    } else {
      
      $settings = \ToolSettingsAPI::getToolSettings(4);

      $rss = $this->getMainRss($settings);

      
      if ($settings->rssActive) {
        $items = $this->getRssItems($settings);
        $this->savePubDateArray();
        foreach ($items as $item) {
          if (null != $item) {
            $rss->addRssItem($item);
          }
        }
      }

      $xml = $rss->getRss();

      if ($this->useCache()) {
        $this->setCache($xml);
      }

      return $xml;
    }
  }

  
  private function isCached(): bool
  {
    $age = time() - 12 * 60 * 60; 

    return file_exists($this->cacheFile) && (filemtime($this->cacheFile) > $age);
  }

  private function getCachedContent(): string
  {
    $fw = new \SimpleFileWork();
    $fw->filename = $this->cacheFile;
    $fw->getContent();

    return $fw->content;
  }

  private function setCache(string $pContent): void
  {
    $fw = new \SimpleFileWork();
    $fw->filename = $this->cacheFile;
    $fw->access = 'w+';
    $fw->openFile();
    $fw->content = $pContent;
    $fw->setContent();
    $fw->closeFile();
  }

  public function clearCache(): void
  {
    if (file_exists($this->cacheFile)) {
      unlink($this->cacheFile);
    }
  }

  
  private function createPubDateArray(): array
  {
    $arrayPubDate = array();
    if (file_exists($this->cachePudateFile)) {
      $lines = file($this->cachePudateFile);
      foreach ($lines as $l) {
        if (trim($l) != '') {
          $parts = explode(':', $l);
          $arrayPubDate[trim($parts[0])] = trim($parts[1]);
        }
      }
    }

    return $arrayPubDate;
  }

  
  private function savePubDateArray(): void
  {
    $fw = new \SimpleFileWork();
    $fw->filename = $this->cachePudateFile;
    $fw->content = '';
    $fw->access = 'w';
    foreach ($this->arrayPubDateNeeded as $id => $timestamp) {
      $fw->content .= trim($id) . ':' . trim($timestamp) . "\n";
    }
    $fw->openFile();
    $fw->setContent();
    $fw->closeFile();
  }

  protected function getPubDateForId(string $id): int
  {
    if (array_key_exists($id, $this->arrayPubDate)) {
      $timestamp = $this->arrayPubDate[$id];
    } else {
      $timestamp = time();
    }

    $this->arrayPubDateNeeded[$id] = $timestamp;

    return $timestamp;
  }

  protected function formatDateTimes(\KursWebUebersichtSettings $settings, string $uhrzeit, \DateTime $datetime): string
  {
    $monatkurz = \DateTimeOperations::getNameofMonthShort($datetime->format('n'));
    $monatlang = \DateTimeOperations::getNameofMonth($datetime->format('n'));

    $komma = $uhrzeit == '' ? '' : ', ';
    switch ($settings->rssSelectWhatBeginn) {
      case 'langDavor':
        return $uhrzeit . $komma . $datetime->format('d.m.Y ');
      case 'langDanach':
        return $datetime->format(' d.m.Y') . $komma . $uhrzeit;
      case 'kurzerMonatDavor':
        return $uhrzeit . $komma . $datetime->format('d. ') . $monatkurz . $datetime->format(' Y ');
      case 'kurzerMonatDanach':
        return $datetime->format(' d. ') . $monatkurz . $datetime->format(' Y') . $komma . $uhrzeit;
      case 'langerMonatDavor':
        return $uhrzeit . $komma . $datetime->format('d. ') . $monatlang . $datetime->format(' Y ');
      case 'langerMonatDanach':
        return $datetime->format(' d. ') . $monatlang . $datetime->format(' Y') . $komma . $uhrzeit;
      default:
        return '';
    }
  }

  
  protected function getNamespaceAttributes($settings): string
  {
    if (\DBWorkBASysSettings::isWittenbergPaulGerhard() && isset($settings->rssDtdUrl) && trim($settings->rssDtdUrl) != '') {
      $dtdurl = $settings->rssDtdUrl;

      return 'xmlns:jsd="' . $dtdurl . '"';
    } else {
      return '';
    }
  }

  
  protected function getMainRss($settings): Rss
  {
    $rss = new Rss();
    $rss->title = $settings->rssTitle;
    $rss->link = 'http://' . $_SERVER['SERVER_NAME'];
    $rss->description = $settings->rssDescr;
    $rss->pubdate = date('r');
    $rss->namespaceAttributes = $this->getNamespaceAttributes($settings);

    return $rss;
  }
}