<?php

class PageMeasure extends Page
{
  public array $GraphTimeRanges;
  public array $DefaultVariables;
  public int $ImageHeight;
  public int $ImageWidth;

  function __construct(System $System)
  {
    parent::__construct($System);
    $this->Title = 'Grafy';
    $this->Description = 'Časové grafy veličin';
    $this->ImageWidth = 800;
    $this->ImageHeight = 200;
    $this->ParentClass = 'PagePortal';
    $this->DefaultVariables = array(
      'TimeSpecify' => 0,
      'Period' => 'day',
      'Measure' => 1,
      'Differential' => 0,
    );
    $this->GraphTimeRanges = array
    (
      'hour' => array(
        'caption' => 'Hodina',
        'period' => 3600,
      ),
      'day' => array(
        'caption' => 'Den',
        'period' => 86400, // 3600 * 24,
      ),
      'week' => array(
        'caption' => 'Týden',
        'period' => 604800, // 3600 * 24 * 7,
      ),
      'month' => array(
        'caption' => 'Měsíc',
        'period' => 2592000, // 3600 * 24 * 30,
      ),
      'year' => array(
        'caption' => 'Rok',
        'period' => 31536000, // 3600 * 24 * 365,
      ),
      'years' => array(
        'caption' => 'Desetiletí',
        'period' => 315360000, // 3600 * 24 * 365 * 10,
      ),
    );
  }

  function EditTime($Time)
  {
    global $MonthNames;

    $Output = '<form style="display: inline;" action="?Operation=SetTime&amp;Time='.$Time.'" method="post">';

    $TimeParts = getdate($_SESSION[$Time]);

    // Day selection
    $Output .= '<select name="Day">';
    for ($I = 1; $I < 32; $I++)
    {
      if ($I == $TimeParts['mday']) $Selected = ' selected="1"'; else $Selected = '';
      $Output .= '<option value="'.$I.'"'.$Selected.'>'.$I.'</option>';
    }
    $Output .= '</select>. ';

    // Month selection
    $Output .= '<select name="Month">';
    foreach ($MonthNames as $Index => $Month)
    {
      if ($Index == $TimeParts['mon']) $Selected = ' selected="1"'; else $Selected = '';
      if ($Index > 0) $Output .= '<option value="'.$Index.'"'.$Selected.'>'.$Month.'</option>';
    }
    $Output .= '</select>. ';

    // Day selection
    $Output .= '<select name="Year">';
    for ($I = 2000; $I < 2010; $I++)
    {
      if ($I == $TimeParts['year']) $Selected = ' selected="1"'; else $Selected = '';
      $Output .= '<option value="'.$I.'"'.$Selected.'>'.$I.'</option>';
    }
    $Output .= '</select> &nbsp;&nbsp; ';

    // Hour selection
    $Output .= '<select name="Hour">';
    for ($I = 0; $I < 24; $I++)
    {
      if ($I == $TimeParts['hours']) $Selected = ' selected="1"'; else $Selected = '';
      $Output .= '<option value="'.$I.'"'.$Selected.'>'.$I.'</option>';
    }
    $Output .= '</select> : ';

    // Minute selection
    $Output .= '<select name="Minute">';
    for ($I = 0; $I < 60; $I++)
    {
      if ($I == $TimeParts['minutes']) $Selected = ' selected="1"'; else $Selected = '';
      $Output .= '<option value="'.$I.'"'.$Selected.'>'.$I.'</option>';
    }
    $Output .= '</select> ';
    $Output .= '<input type="submit" value="Nastavit">';
    $Output .= '</form>';

    $Output .= ' <form style="display: inline;" action="?Operation=SetTimeNow&amp;Time='.$Time.'" method="post">';
    $Output .= '<input type="submit" value="Aktuální čas">';
    $Output .= '</form>';

    return $Output;
  }

  function Show(): string
  {
    $Debug = 0;

    foreach ($this->DefaultVariables as $Index => $Variable)
    {
      if (!array_key_exists($Index, $_SESSION)) $_SESSION[$Index] = $Variable;
      if (array_key_exists($Index, $_GET)) $_SESSION[$Index] = $_GET[$Index];
      if (array_key_exists($Index, $_POST)) $_SESSION[$Index] = $_POST[$Index];
      //$$Index = $_SESSION[$Index];
    }

    if ($_SESSION['TimeSpecify'] == 0)
    {
      $_SESSION['TimeEnd'] = time() - 60;
      $_SESSION['TimeStart'] = $_SESSION['TimeEnd'] - $this->GraphTimeRanges[$_SESSION['Period']]['period'];
    }

    $Output = '<div style="text-align: center;">';

    if (!array_key_exists('Operation', $_GET)) $_GET['Operation'] = '';
    switch ($_GET['Operation'])
    {
      case 'SetTime':
        if (array_key_exists('Time', $_GET) and array_key_exists('Month', $_POST) and array_key_exists('Day', $_POST) and
          array_key_exists('Year', $_POST) and array_key_exists('Hour', $_POST) and array_key_exists('Minute', $_POST))
        {
          if (($_GET['Time'] == 'TimeStart') or ($_GET['Time'] == 'TimeEnd'))
          {
            $_SESSION[$_GET['Time']] = mktime($_POST['Hour'], $_POST['Minute'], 0, $_POST['Month'],
              $_POST['Day'], $_POST['Year']);
            $$_GET['Time'] = $_SESSION[$_GET['Time']];
          }
        }
        break;
      case 'SetTimeNow':
        if (array_key_exists('Time', $_GET))
        {
          if (($_GET['Time'] == 'TimeStart') or ($_GET['Time'] == 'TimeEnd'))
          {
            $_SESSION[$_GET['Time']] = time();
            $$_GET['Time'] = $_SESSION[$_GET['Time']];
          }
        }
        break;
    }
    $Output .= '<strong>Časový úsek:</strong><br>';
    // Show graf time range menu
    if ($_SESSION['TimeSpecify'] == 0)
    {
      $Output .= 'Délka úseku: ';
      foreach ($this->GraphTimeRanges as $Index => $Item)
        $Output .= '<a href="?Period='.$Index.'">'.$Item['caption'].'</a>&nbsp;';
      $Output .= '<br/>';
      $Output .= '<a href="?TimeSpecify=1">Přesnější nastavení...</a><br>';
    } else {
      $Output .= '<table style="margin: 10px auto; " cellspacing="0" cellpadding="2" border="0">';
      $Output .= '<tr><td>Počátek:</td><td>'.$this->EditTime('TimeStart').'</td></tr>';
      $Output .= '<tr><td>Konec:</td><td>'.$this->EditTime('TimeEnd').'</td></tr>';
      $Output .= '</table>';
      $Output .= '<a href="?TimeSpecify=0">Jednoduché nastavení...</a><br>';
    }
    $Output .= '<br/>'.$this->Graph();

    $Output .= '<br/>'.$this->MeasureTable();
    return $Output;
  }

  function Graph(): string
  {
    $Output = '<strong>Graf:</strong><br/>';
    $Output .= '<img alt="Graf" src="'.$this->System->Link('/grafy/graf.png?Measure='.$_SESSION['Measure'].
      '&amp;From='.$_SESSION['TimeStart'].'&amp;To='.$_SESSION['TimeEnd'].'&amp;Width='.
      $this->ImageWidth.'&amp;Height='.$this->ImageHeight.'&amp;Differential='.
      $_SESSION['Differential']).'" width="'.$this->ImageWidth.'" height="'.$this->ImageHeight.'"><br>';
    $Output .= '<a href="?Measure='.$_SESSION['Measure'].'&amp;TimeStart='.
      $_SESSION['TimeStart'].'&amp;TimeEnd='.$_SESSION['TimeEnd'].'&amp;TimeSpecify=1&amp;Differential='.$_SESSION['Differential'].'">Odkaz na vybraný graf</a><br>';
    return $Output;
  }

  function MeasureTable(): string
  {
    $PrefixMultiplier = new PrefixMultiplier();

    $DbResult = $this->Database->query('SELECT COUNT(*) FROM `Measure` WHERE `Enabled`=1');
    $DbRow = $DbResult->fetch_row();
    $PageList = GetPageList('Measures', $DbRow[0]);

    $Output = $PageList['Output'];
    $Output .= '<table class="WideTable" style="font-size: small;">';

    $TableColumns = array(
      array('Name' => 'Name', 'Title' => 'Měřená veličina'),
      array('Name' => 'LastValue', 'Title' => 'Poslední hodnota'),
      array('Name' => 'LastValueTime', 'Title' => 'Čas posledního měření'),
      array('Name' => 'Continuous', 'Title' => 'Interpolace'),
      array('Name' => 'Description', 'Title' => 'Popis'),
    );
    if (array_key_exists('Debug', $_GET))
    {
      $TableColumns[] = array('Name' => 'ItemCount', 'Title' => 'Počet položek');
      $TableColumns[] = array('Name' => 'MeasureDuration', 'Title' => 'Čas vykonání');
    }
    $Order = GetOrderTableHeader('Measures', $TableColumns, 'Name', 0);
    $Output .= $Order['Output'];

    $Result = $this->Database->select('Measure', '*', '`Enabled`=1 '.$Order['SQL'].$PageList['SQLLimit']);
    while ($Measure = $Result->fetch_array())
    {
      $DbResult2 = $this->Database->select('MeasureMethod', '*', '`Id`='.$Measure['Method']);
      $MeasureMethod = $DbResult2->fetch_assoc();
      $StopWatchStart = GetMicrotime();
      if (array_key_exists('Debug', $_GET))
      {
        $DbResult = $this->Database->select($Measure['DataTable'], 'COUNT(*)', 'Measure='.$Measure['Id']);
        $RowCount = $DbResult->fetch_array();
        $RowCount = $RowCount[0];
      }
      $Result2 = $this->Database->select($Measure['DataTable'], 'Time, Avg', 'Measure='.$Measure['Id'].' AND Level=0 ORDER BY Time DESC LIMIT 1');
      if ($Result2->num_rows > 0)
      {
        $Row = $Result2->fetch_array();
        $LastMeasureTime = date('j.n.Y G:i:s', MysqlDateTimeToTime($Row['Time']));
        $LastMeasureValue = $PrefixMultiplier->Add($Row['Avg'], $MeasureMethod['Unit']);
      } else
      {
        $LastMeasureTime = '&nbsp;';
        $LastMeasureValue = '&nbsp;';
      }
      if ($Measure['Continuity'] == 1) $Interpolate = 'Ano';
        else $Interpolate = 'Ne';
      //if ($Measure['Description'] == '') $Measure['Description'] = '&nbsp;';
      $GenerationTime = floor((GetMicrotime() - $StopWatchStart) * 1000  ) / 1000;
      $Output .= '<tr><td><a href="?Measure='.$Measure['Id'].'&amp;Differential=0">'.$Measure['Name'].'</a></td><td align="center">'.$LastMeasureValue.'</td><td align="center">'.$LastMeasureTime.'</td><td align="center">'.$Interpolate.'</td><td>'.$Measure['Description'].'</td>';
      if (array_key_exists('Debug', $_GET)) $Output .= '<td>'.$RowCount.'</td><td>'.$GenerationTime.'</td>';
      $Output .= '</tr>';
    }
    $Output .= '</table>';
    $Output .= $PageList['Output'];
    
    //ShowPage($Output);    
    $Output .= '</div>';
    return $Output;
  }
}

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

    $Output = '';
    if (!array_key_exists('MeasureId', $_GET)) return 'Nebylo zadáno Id měření.';
    if (!array_key_exists('Value', $_GET)) return 'Nebyla zadána hodnota.';
    $Measure = new Measure($this->System);
    $Measure->Load($_GET['MeasureId']);
    if (!isset($Measure->Data['Id'])) return 'Měření s Id '.$_GET['MeasureId'].' nenalezeno.';
    $Measure->AddValue(array('Min' => $_GET['Value'], 'Avg' => $_GET['Value'], 'Max' => $_GET['Value']));
    return $Output;
  }
}
