<?php

class ModuleExport extends Module
{
  function __construct(System $System)
  {
    parent::__construct($System);
    $this->Name = 'Export';
    $this->Version = '1.0';
    $this->Creator = 'Chronos';
    $this->License = 'GNU/GPL';
    $this->Description = 'Allow parametric export of translated texts to various supported output formats';
    $this->Dependencies = array('Translation');
  }

  function DoStart(): void
  {
    $this->System->RegisterPage(['export'], 'PageExport');
    $this->System->RegisterPage(['export', 'progress'], 'PageExportProgress');
    Core::Cast($this->System)->RegisterMenuItem(array(
      'Title' => 'Exporty',
      'Hint' => 'Zde si můžete stáhnout přeložené texty',
      'Link' => $this->System->Link('/export/'),
      'Permission' => LICENCE_ANONYMOUS,
      'Icon' => '',
    ), 2);
  }

  function GetTaskProgress($TaskId)
  {
    $Output = '';
    $DbResult = $this->Database->query('SELECT * FROM `ExportTask` '.
      'LEFT JOIN `Export` ON `Export`.`Id` = `ExportTask`.`Export` WHERE '.
      '((`Export`.`OutputType` = 9) OR (`Export`.`OutputType` = 10)) AND '.
      '(`TimeFinish` IS NULL) OR (`Export` ='.$TaskId.') ORDER BY `TimeQueued`'); // `Export`='.$Export->Id
    while ($Task = $DbResult->fetch_assoc())
    {
      $Export = '<a href="'.$this->System->Link('/export/?Action=View&amp;ExportId='.$Task['Export']).'">'.$Task['Export'].'</a>';
      if ($TaskId == $Task['Export'])
        $Export = ''.$Export.' (tento)';

      // Show progress bar
      $Output .= ' <strong>Export '.$Export.':</strong> <div id="progress'.$Task['Export'].'">'.
        '<strong>'.ProgressBar(300, $Task['Progress']).'</strong> ';

      // Show estimated time to complete
      $PrefixMultiplier = new PrefixMultiplier();
      if ($Task['Progress'] > 0) 
      {
        $ElapsedTime = time() - MysqlDateTimeToTime($Task['TimeStart']);
        $Output .= T('Elapsed time').': <strong>'.$PrefixMultiplier->Add($ElapsedTime, '', 4, 'Time').'</strong> / ';
        $EstimatedTime = (time() - MysqlDateTimeToTime($Task['TimeStart'])) / $Task['Progress'] * (100 - $Task['Progress']);
        $Output .= T('Estimated remaining time').': <strong>'.$PrefixMultiplier->Add($EstimatedTime, '', 4, 'Time').'</strong><br/>';
      }
      $Output .= '</div>';

      if ($Task['Progress'] > 99)
        $Output .= '<script type="text/javascript" language="JavaScript" charset="utf-8">'.
        'setTimeout("parent.location.href=\''.$this->System->Link('/export/?Action=View&Tab=7&ExportId='.$TaskId).'\'", 500)'.
        '</script>';
    }
    return $Output;
  }
}
