<?php

class ModuleRSS extends Module
{
  public array $RSSChannels;
  public array $RSSChannelsPos;
  
  function __construct(System $System)
  {
    parent::__construct($System);
    $this->Name = 'RSS';
    $this->Version = '1.0';
    $this->Creator = 'Chronos';
    $this->License = 'GNU/GPLv3';
    $this->Description = 'Web site RSS channel management';
    $this->RSSChannels = array();
    $this->RSSChannelsPos = array();
  }

  function DoStart(): void
  {
    $this->System->RegisterPage(['rss'], 'PageRSS');
    Core::Cast($this->System)->RegisterPageHeader('RSS', array($this, 'ShowRSSHeader'));
  }

  function RegisterRSS(array $Channel, $Pos = NULL, $Callback = NULL): void
  {
    $this->RSSChannels[$Channel['Channel']] = $Channel;

    if (is_null($Pos)) $this->RSSChannelsPos[] = $Channel['Channel'];
    else
    {
      array_splice($this->RSSChannelsPos, $Pos, 0, $Channel['Channel']);
    }
  }

  function UnregisterRSS($ChannelName): void
  {
    unset($this->RSSChannels[$ChannelName]);
    // TODO: Remove channel from pos list
  }

  function ShowRSSHeader(): string
  {
    $Output = '';
    foreach ($this->RSSChannels as $Channel)
    {
      //if (ModuleUser::Cast($this->System->GetModule('User'))->User->Licence($Channel['Permission']))
        $Output .= ' <link rel="alternate" title="'.$Channel['Title'].'" href="'.
          $this->System->Link('/rss/?channel='.$Channel['Channel']).'" type="application/rss+xml" />';
    }
    return $Output;
  }

  static function Cast(Module $Module): ModuleRSS
  {
    if ($Module instanceof ModuleRSS)
    {
      return $Module;
    }
    throw new Exception('Expected ModuleRSS type but got '.gettype($Module));
  }
}

class PageRSS extends Page
{
  function Show(): string
  {
    $this->RawPage = true;

    if (array_key_exists('channel', $_GET)) $ChannelName = $_GET['channel'];
      else $ChannelName = '';
    if (array_key_exists('token', $_GET)) $Token = $_GET['token'];
      else $Token = '';      
    if (array_key_exists($ChannelName, ModuleRSS::Cast($this->System->GetModule('RSS'))->RSSChannels))
    {
      $Channel = ModuleRSS::Cast($this->System->GetModule('RSS'))->RSSChannels[$ChannelName];
      if (ModuleUser::Cast($this->System->GetModule('User'))->User->CheckPermission($Channel['Permission']['Module'], $Channel['Permission']['Operation']) or
      ModuleUser::Cast($this->System->GetModule('User'))->User->CheckToken($Channel['Permission']['Module'], $Channel['Permission']['Operation'], $Token))
      {
        if (is_string($Channel['Callback'][0]))
        {
          $Class = new $Channel['Callback'][0]($this->System);
          $Method = $Channel['Callback'][1];
          $Output = $Class->$Method();
        } else $Output = call_user_func($Channel['Callback']);
      } else $Output = 'Nemáte oprávnění';
    } else $Output = 'Kanál nenalezen';
    return $Output;
  }
}
