<?php

include_once(dirname(__FILE__).'/Comparison.php');
include_once(dirname(__FILE__).'/Form.php');
include_once(dirname(__FILE__).'/Save.php');
include_once(dirname(__FILE__).'/TranslationList.php');
include_once(dirname(__FILE__).'/Progress.php');
include_once(dirname(__FILE__).'/LoadNames.php');
include_once(dirname(__FILE__).'/UserLevel.php');

class ModuleTranslation extends Module
{
  public array $TranslationTree;

  function __construct(System $System)
  {
    parent::__construct($System);
    $this->Name = 'Translation';
    $this->Version = '1.0';
    $this->Creator = 'Chronos';
    $this->License = 'GNU/GPL';
    $this->Description = 'Translation of text items and groups from original language to other languages.';
    $this->Dependencies = array('News', 'Search');
  }

  function DoStart(): void
  {
    $this->System->RegisterPage(['comparison.php'], 'PageTranslationComparison');
    $this->System->RegisterPage(['form.php'], 'PageTranslationForm');
    $this->System->RegisterPage(['save.php'], 'PageTranslationSave');
    $this->System->RegisterPage(['progress'], 'PageProgress');
    $this->System->RegisterPage(['translation-groups'], 'PageTranslationGroups');
    $this->System->RegisterPage(['TranslationList.php'], 'PageTranslationList');
    $this->System->RegisterPage(['LoadNames.php'], 'PageLoadNames');
    $this->System->ModuleManager->Modules['News']->RegisterRSS(array('Title' => T('Last translations'),
      'Channel' => 'translation', 'Callback' => array($this, 'ShowRSS'), 'Permission' => LICENCE_ANONYMOUS));
    Core::Cast($this->System)->RegisterMenuItem(array(
      'Title' => T('Completion status'),
      'Hint' => 'Stav dokončení překládů',
      'Link' => $this->System->Link('/progress/'),
      'Permission' => LICENCE_ANONYMOUS,
      'Icon' => '',
    ), 1);
    Core::Cast($this->System)->RegisterMenuItem(array(
      'Title' => T('Data source'),
      'Hint' => 'Informace o překladových skupinách',
      'Link' => $this->System->Link('/translation-groups/'),
      'Permission' => LICENCE_ANONYMOUS,
      'Icon' => '',
    ));
    if (array_key_exists('Search', $this->System->ModuleManager->Modules))
    {
      $TranslationTree = $this->System->ModuleManager->Modules['Translation']->GetTranslationTree();
      foreach ($TranslationTree as $Group)
      {
        $Table = $Group['TablePrefix'];

        $Columns = array('ID', 'Entry');
        foreach ($Group['Items'] as $Item)
        {
          if ($Item['Column'] != '') $Columns[] = $Item['Column'];
        }

        $this->System->ModuleManager->Modules['Search']->RegisterSearch('group'.$Group['Id'],
          sprintf(T('Translation group "%s"'), $Group['Name']), $Columns, '`'.$Table.'`',
          $this->System->Link('/TranslationList.php?group='.
          $Group['Id'].'&amp;user=0&amp;state=0&amp;entry=&amp;text='));
      }
    }
    Core::Cast($this->System)->RegisterPageBarItem('Right', 'TranslatedMenu', array($this, 'ShowTranslatedMenu'));
  }

  function ShowRSS()
  {
    $Items = array();
    $DbResult = $this->Database->query('SELECT UNIX_TIMESTAMP(`Date`) AS `Date`, `User`.`Name` AS `UserName`, `Text` FROM `Log` '.
    'JOIN `User` ON `User`.`ID` = `Log`.`User` WHERE `Type` = 1 ORDER BY `Date` DESC LIMIT 100');
    while ($DbRow = $DbResult->fetch_assoc())
    {
      $Items[] = array
      (
        'Title' => strip_tags($DbRow['Text'].' ('.$DbRow['UserName'].')'),
        'Link' => 'http://'.Core::Cast($this->System)->Config['Web']['Host'].$this->System->Link('/'),
        'Description' => $DbRow['Text'],
        'Time' => $DbRow['Date'],
      );
    }
    $Output = GenerateRSS(array
    (
      'Title' => Core::Cast($this->System)->Config['Web']['Title'].' - '.T('Last translations'),
      'Link' => 'https://'.Core::Cast($this->System)->Config['Web']['Host'].$this->System->Link('/'),
      'Description' => Core::Cast($this->System)->Config['Web']['Description'],
      'WebmasterEmail' => Core::Cast($this->System)->Config['Web']['AdminEmail'],
      'Items' => $Items,
    ));
    return $Output;
  }

  function ShowBox()
  {
    $Count = 40;
    $Output = '<strong>'.T('Last translated').':</strong>';
    $Output .= '<div class="box">';

    $GroupListQuery = 'SELECT `Group`.* FROM `Group`';
    $Query = '';
    $UnionItems = array();
    $DbResult = $this->Database->query($GroupListQuery);
    if ($DbResult->num_rows > 0)
    {
      while ($DbRow = $DbResult->fetch_assoc())
      {
        $UnionItems[] = 'SELECT `T`.`ID`, `T`.`Take`, `T`.`User`, `T`.`ModifyTime`, `T`.`Group`, `T`.`GroupName` '.
            'FROM (SELECT `T`.`User`, `T`.`ID`, `T`.`ModifyTime`, '.
            $DbRow['Id'].' AS `Group`, "'.addslashes($DbRow['Name']).'" AS `GroupName`, `T`.`Take` FROM `'.
            $DbRow['TablePrefix'].'` AS `T`'.
            ' WHERE (`T`.`Complete` = 1) AND (`T`.`Language` != '.Core::Cast($this->System)->Config['OriginalLanguage'].') ORDER BY `T`.`ModifyTime` DESC LIMIT '.
            $Count.') AS `T`';
      }
      $Query = 'SELECT `TT`.*, `User`.`Name` AS `UserName`, `User`.`Id` AS `UserId` '.
          ' FROM ('.implode(' UNION ', $UnionItems).') AS `TT`'.
          ' JOIN `User` ON `User`.`Id` = `TT`.`User`'.
          ' ORDER BY `ModifyTime` DESC LIMIT '.$Count;
      $DbResult = $this->Database->query($Query);
      $Output .= '<table class="MiniTable"><tr><th>'.T('Date').'</th><th>'.T('Who').'</th><th>'.T('New').'</th><th>'.T('Source').'</th><th>'.T('Group').'</th></tr>';
      while ($DbRow = $DbResult->fetch_assoc())
      {
        $Output .= '<tr><td>'.HumanDate($DbRow['ModifyTime']).'</td>'.
            '<td><a href="'.$this->System->Link('/user/?user='.$DbRow['UserId']).'">'.$DbRow['UserName'].'</a></td>'.
            '<td><a href="'.$this->System->Link('/form.php?group='.$DbRow['Group'].'&amp;ID='.$DbRow['ID']).'">'.$DbRow['ID'].'</a></td>'.
            '<td><a href="'.$this->System->Link('/form.php?group='.$DbRow['Group'].'&amp;ID='.$DbRow['Take']).'">'.$DbRow['Take'].'</a></td>'.
            '<td><a href="'.$this->System->Link('/TranslationList.php?group='.$DbRow['Group'].'&amp;action=filter').'">'.T($DbRow['GroupName']).'</a></td></tr>';
      }
      $Output .= '</table>';
    }
    $Output .= '</div>';
    return $Output;
  }

  function GetTranslationTree()
  {
    if (isset($this->TranslationTree)) return $this->TranslationTree;
    else 
    {
      $Result = array();
      $Groups = array();
      $DbResult = $this->System->Database->query('SELECT *, UNIX_TIMESTAMP(`LastImport`) AS `LastImportTime` FROM `Group`');
      while ($DbRow = $DbResult->fetch_assoc())
        $Groups[T($DbRow['Name'])] = $DbRow;
      ksort($Groups);
      foreach ($Groups as $Group)
      {
        $Group['Items'] = array();
        $Group['Game'] = T($Group['Name']);
        $Result[$Group['Id']] = $Group;
      }
      $DbResult = $this->System->Database->query('SELECT * FROM `GroupItem` ORDER BY `Group`, `Sequence`');
      while ($DbRow = $DbResult->fetch_assoc())
      {
        $Result[$DbRow['Group']]['Items'][] = $DbRow;
      }
      $this->TranslationTree = $Result;
      return $Result;
    }
  }

  function ShowTranslatedMenu()
  {
    $User = ModuleUser::Cast($this->System->GetModule('User'))->User;
    $TranslationTree = $this->GetTranslationTree();

    $Output = '<strong>'.T('Translate groups').':</strong><br /><div id="TranslationMenu">';
    $DbResult = $this->System->Database->select('Group', '`Id`, `Name`', '1 ORDER BY `Name`');
    while ($Group = $DbResult->fetch_assoc())
    {
      $Groups[T($Group['Name'])] = $Group;
    }
    ksort($Groups);
    foreach ($Groups as $Group)
    {
      $Output .= '<div id="menuitem-group'.$Group['Id'].'" onmouseover="show(\'group'.$Group['Id'].'\')" onmouseout="hide(\'group'.$Group['Id'].'\')">'.
        '<a href="'.$this->System->Link('/TranslationList.php?group='.$Group['Id'].
          '&amp;action=filter').'">'.str_replace(' ','&nbsp;', T($Group['Name'])).'</a></div>'.
          '<div id="group'.$Group['Id'].'" class="hidden-menu-item" onmouseover="show(\'group'.$Group['Id'].'\')" onmouseout="hide(\'group'.$Group['Id'].'\')">';
      $Output .= '&nbsp;<a title="Zde můžete začít překládat" href="'.
        $this->System->Link('/TranslationList.php?group='.$Group['Id'].'&amp;state=1&amp;user=0&amp;entry=&amp;text=').'">'.T('Untranslated').'</a><br />'.
        '&nbsp;<a title="Přeložené texty, můžete zde hlasovat, nebo opravovat překlady" href="'.
        $this->System->Link('/TranslationList.php?group='.$Group['Id'].'&amp;state=2&amp;user=0&amp;entry=&amp;text=').'">'.T('Translated').'</a><br />';
      if (isset($User) and $User->Licence(LICENCE_USER))
      {
        $Output .= '&nbsp;<a title="'.T('Unfinished translations').'" href="'.$this->System->Link('/TranslationList.php?group='.$Group['Id'].'&amp;state=3').'">'.T('Unfinished').'</a><br />'.
          '&nbsp;<a title="Všechny překlady, které jste přeložil" href="'.
          $this->System->Link('/TranslationList.php?group='.$Group['Id'].'&amp;state=1&amp;user='.
          $User->Id).'&amp;entry=&amp;text=">'.T('Own').'</a><br />';
      }
      $Output .= '&nbsp;<a title="'.T('Compose special filter').'" href="'.
        $this->System->Link('/TranslationList.php?group='.$Group['Id'].'&amp;action=filter').
        '">'.T('Filter').'</a><br />';
        $Output .= '</div>';
    }
    $Output .= '</div>';
    return $Output;
  }

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