<?php

class Measure extends Model
{
  public array $Data;
  public int $LevelReducing = 5;
  public int $ReferenceTime = 0;
  public int $MaxLevel = 4;
  public int $Differential = 0;
  public int $Debug = 0;
  public int $DivisionCount = 500;
  public array $ValueTypes = array('Min', 'Avg', 'Max');

  static function GetModelDesc(): ModelDesc
  {
    $Desc = new ModelDesc(self::GetClassName());
    $Desc->AddString('Name');
    $Desc->AddString('Title');
    $Desc->AddString('Description');
    $Desc->AddString('Unit');
    $Desc->AddBoolean('Continuity');
    $Desc->AddInteger('Period');
    $Desc->AddString('PermissionAdd');
    $Desc->AddString('PermissionView');
    $Desc->AddBoolean('Enabled');
    $Desc->AddString('DataType');
    $Desc->AddString('DataTable');
    return $Desc;
  }

  function Load(int $Id): void
  {
    $Result = $this->Database->select('Measure', '*', 'Id='.$Id);
    if ($Result->num_rows > 0)
    {
      $this->Data = $Result->fetch_assoc();
      if ($this->Data['Continuity'] == 0) $this->Data['ContinuityEnabled'] = 0;  // non continuous
        else $this->Data['ContinuityEnabled'] = 2;    // continuous graph
    } else throw new Exception('Measure not found');
  }

  function TimeSegment($Base, $Level)
  {
    return pow($this->LevelReducing, $Level) * $Base;
  }

  function StatTableName(int $Level): string
  {
    if ($Level == 0) return 'Data';
      else return 'DataCache';
  }

  function AlignTime($Time, $TimeSegment)
  {
    return round(($Time - $this->ReferenceTime) / $TimeSegment) * $TimeSegment + $this->ReferenceTime;
  }

  function AddValue($Value = array('Min' => 0, 'Avg' => 0, 'Max' => 0), $Level = 0, $Time = 0)
  {
    if ($Time == 0) $Time = time();

    $Result = $this->Database->select($this->Data['DataTable'], '*', 'Measure='.
      $this->Data['Id'].' AND Level='.$Level.' ORDER BY Time DESC LIMIT 2');
    if ($Result->num_rows == 0)
    {
       $this->Database->insert($this->Data['DataTable'], array('Min' => $Value['Min'],
         'Avg' => $Value['Avg'], 'Max' => $Value['Max'], 'Level' => $Level,
         'Measure' => $this->Data['Id'], 'Time' => TimeToMysqlDateTime($Time), 'Continuity' => 0));
    } else if ($Result->num_rows == 1)
    {
      $this->Database->insert($this->Data['DataTable'], array('Min' => $Value['Min'],
        'Avg' => $Value['Avg'], 'Max' => $Value['Max'], 'Level' => $Level,
        'Measure' => $this->Data['Id'], 'Time' => TimeToMysqlDateTime($Time), 'Continuity' => 1));
    } else
    {
      $LastValue = $Result->fetch_assoc();
      $NextToLastValue = $Result->fetch_assoc();
      if ((($Time - MysqlDateTimeToTime($LastValue['Time'])) < 0.75 * $this->Data['Period']) and ($Level == 0))
      {
        echo('Too short period. Minimal period is '.(0.75 * $this->Data['Period'])." seconds\n");
      } else
      {
        if (($Time - MysqlDateTimeToTime($LastValue['Time'])) < 1.25 * $this->Data['Period']) $Continuity = 1;
          else $Continuity = 0;
        if (($LastValue['Min'] == $NextToLastValue['Min']) and ($LastValue['Min'] ==
          $Value['Min']) and ($LastValue['Avg'] == $NextToLastValue['Avg']) and
          ($LastValue['Avg'] == $Value['Avg']) and ($LastValue['Max'] == $NextToLastValue['Max'])
          and ($LastValue['Max'] == $Value['Max']) and ($LastValue['Continuity'] == 1) and ($Continuity == 1))
        {
          $this->Database->update($this->Data['DataTable'], '(Time="'.$LastValue['Time'].
            '") AND (Level='.$Level.') AND (Measure='.$this->Data['Id'].')', array('Time' => TimeToMysqlDateTime($Time)));
        } else
        {
          $this->Database->insert($this->Data['DataTable'], array('Min' => $Value['Min'],
            'Avg' => $Value['Avg'], 'Max' => $Value['Max'], 'Level' => $Level,
            'Measure' => $this->Data['Id'], 'Time' => TimeToMysqlDateTime($Time), 'Continuity' => $Continuity));
        }
      }

      // Update next level
      if ($Level < $this->MaxLevel)
      {
        $Level = $Level + 1;
        $TimeSegment = $this->TimeSegment($this->Data['Period'], 1);
        $EndTime = $this->AlignTime($Time, $TimeSegment);
        //if ($EndTime < $Time) $EndTime = $EndTime + $TimeSegment;
        $StartTime = $EndTime - $TimeSegment;

        // Load values in time range
        $Values = array();
        //.'" AND Time < "'.TimeToMysqlDateTime($EndTime).'" AND Measure='.$Measure['Id'].' AND Level='.($Level - 1).' ORDER BY Time');
        $Result = $this->Database->select($this->Data['DataTable'], '*', '(Time > "'.
          TimeToMysqlDateTime($StartTime).'") AND (Time < "'.TimeToMysqlDateTime($EndTime).
            '") AND (Measure='.$this->Data['Id'].') AND (Level='.($Level - 1).') ORDER BY Time');
        while ($Row = $Result->fetch_assoc())
        {
          $Row['Time'] = MysqlDateTimeToTime($Row['Time']);
          $Values[] = $Row;
        }
        //if (count($Values) > 2)
        {
          //array_pop($Values);

          // Load subsidary values
          $Values = array_merge($this->LoadLeftSideValue($Level - 1,
            $StartTime), $Values, $this->LoadRightSideValue($Level - 1, $EndTime));

          $Point = $this->ComputeOneValue($StartTime, $EndTime, $Values, $Level);

          $this->Database->delete($this->Data['DataTable'], '(Time > "'.TimeToMysqlDateTime($StartTime).
            '") AND (Time < "'.TimeToMysqlDateTime($EndTime).'") AND Measure='.$this->Data['Id'].' AND Level='.$Level);
          $this->Data['Period'] = $TimeSegment;
          $this->AddValue(array('Min' => $Point['Min'], 'Avg' => $Point['Avg'],
            'Max' => $Point['Max']), $Level, $StartTime + ($EndTime - $StartTime) / 2);
        }
      }
    }
  }

  function Interpolation($X1, $Y1, $X2, $Y2, $X)
  {
    $Y = ($Y2 - $Y1) / ($X2 - $X1) * ($X - $X1) + $Y1;
    return $Y;
  }

  function ComputeOneValue($LeftTime, $RightTime, $Values, $Level)
  {
    $NewValue = array('Min' => +1000000000000000000, 'Avg' => 0, 'Max' => -1000000000000000000);

    // Trim outside parts
    foreach ($this->ValueTypes as $ValueType)
    {
      $Values[0][$ValueType] = $this->Interpolation($Values[0]['Time'], $Values[0][$ValueType], $Values[1]['Time'], $Values[1][$ValueType], $LeftTime);
    }
    $Values[0]['Time'] = $LeftTime;
    foreach ($this->ValueTypes as $ValueType)
    {
        $Values[count($Values) - 1][$ValueType] = $this->Interpolation($Values[count($Values) - 2]['Time'], $Values[count($Values) - 2][$ValueType],
        $Values[count($Values) - 1]['Time'], $Values[count($Values) - 1][$ValueType], $RightTime);
    }
    $Values[count($Values) - 1]['Time'] = $RightTime;

    // Perform computation
    foreach ($this->ValueTypes as $ValueType)
    {
      // Compute new value
      for ($I = 0; $I < (count($Values) - 1); $I++)
      {
        if ($ValueType == 'Avg')
        {
          if ($Values[$I + 1]['Continuity'] == $this->Data['ContinuityEnabled']);
          else if ($this->Differential == 0)
          {
            $NewValue[$ValueType] = $NewValue[$ValueType] + ($Values[$I + 1]['Time'] - $Values[$I]['Time']) *
              (($Values[$I + 1][$ValueType] - $Values[$I][$ValueType]) / 2 + $Values[$I][$ValueType]);
          } else
          {
            $NewValue[$ValueType] = $NewValue[$ValueType] + ($Values[$I + 1]['Time'] - $Values[$I]['Time']) *
              (($Values[$I + 1][$ValueType] - $Values[$I][$ValueType]) / 2);
          }
        }
        else if ($ValueType == 'Max')
        {
          if ($Values[$I + 1]['Continuity'] == $this->Data['ContinuityEnabled'])
          {
            if (0 > $NewValue[$ValueType]) $NewValue[$ValueType] = 0;
          } else
          {
            if ($this->Differential == 0)
            {
              if ($Values[$I + 1][$ValueType] > $NewValue[$ValueType]) $NewValue[$ValueType] = $Values[$I + 1][$ValueType];
            } else {
              $Difference = $Values[$I + 1][$ValueType] - $Values[$I][$ValueType];
              if ($Difference > $NewValue[$ValueType]) $NewValue[$ValueType] = $Difference;
            }
          }
        }
        else if ($ValueType == 'Min')
        {
          if ($Values[$I + 1]['Continuity'] == $this->Data['ContinuityEnabled'])
          {
            if (0 < $NewValue[$ValueType]) $NewValue[$ValueType] = 0;
          } else
          {
            if ($this->Differential == 0)
            {
              if ($Values[$I + 1][$ValueType] < $NewValue[$ValueType]) $NewValue[$ValueType] = $Values[$I + 1][$ValueType];
            } else {
              $Difference = $Values[$I + 1][$ValueType] - $Values[$I][$ValueType];
              if ($Difference < $NewValue[$ValueType]) $NewValue[$ValueType] = $Difference;
            }
          }
        }
      }
      $NewValue[$ValueType] = $NewValue[$ValueType];
    }
    //if (($RightTime - $LeftTime) > 0)
    if ($this->Data['Cumulative'] == 0)
    {
      $NewValue['Avg'] = $NewValue['Avg'] / ($RightTime - $LeftTime);
    }
    return $NewValue;
  }

  function GetTimeRange($Level)
  {
    // Get first and last time
    $Result = $this->Database->select($this->Data['DataTable'], '*', 'Measure='.$this->Data['Id'].' AND Level='.$Level.' ORDER BY Time LIMIT 1');
    if ($Result->num_rows > 0)
    {
      $Row = $Result->fetch_assoc();
      $AbsoluteLeftTime = MysqlDateTimeToTime($Row['Time']);
    } else $AbsoluteLeftTime = 0;

    $Result = $this->Database->select($this->Data['DataTable'], '*', 'Measure='.$this->Data['Id'].' AND Level='.$Level.' ORDER BY Time DESC LIMIT 1');
    if ($Result->num_rows > 0)
    {
      $Row = $Result->fetch_assoc();
      $AbsoluteRightTime = MysqlDateTimeToTime($Row['Time']);
    } else $AbsoluteRightTime = 0;

    if ($this->Debug)
    {
      echo('AbsoluteLeftTime: '.$AbsoluteLeftTime.'('.TimeToMysqlDateTime($AbsoluteLeftTime).')<br>');
      echo('AbsoluteRightTime: '.$AbsoluteRightTime.'('.TimeToMysqlDateTime($AbsoluteRightTime).')<br>');
    }
    return array('Left' => $AbsoluteLeftTime, 'Right' => $AbsoluteRightTime);
  }

  function LoadRightSideValue($Level, $Time)
  {
    $Result = array();
    $DbResult = $this->Database->select($this->Data['DataTable'], '*', 'Time > "'.TimeToMysqlDateTime($Time).'" AND Measure='.$this->Data['Id'].' AND Level='.$Level.' ORDER BY Time ASC LIMIT 1');
    if ($DbResult->num_rows > 0)
    {
      $Row = $DbResult->fetch_assoc();
      $Row['Time'] = MysqlDateTimeToTime($Row['Time']);
      return array($Row);
    } else
    {
      //$Time = $Values[count($Values)-1]['Time'] + 60;
      //array_push($Values, array('Time' => $Time, 'Min' => 0, 'Avg' => 0, 'Max' => 0, 'Continuity' => 0));
      $Result[] = array('Time' => ($Time + $this->TimeSegment($this->Data['Period'], $Level)), 'Min' => 0, 'Avg' => 0, 'Max' => 0, 'Continuity' => 0);
      $DbResult = $this->Database->select($this->Data['DataTable'], '*', 'Time < "'.
        TimeToMysqlDateTime($Time).'" AND Measure='.$this->Data['Id'].' AND Level='.$Level.' ORDER BY Time DESC LIMIT 1');
      if ($DbResult->num_rows > 0)
      {
        $Row = $DbResult->fetch_assoc();
        array_unshift($Result, array('Time' => (MysqlDateTimeToTime($Row['Time']) + 10), 'Min' => 0, 'Avg' => 0, 'Max' => 0, 'Continuity' => 0));
      }
     // if ($Debug) print_r($Result);
      return $Result;
    }
  }

  function LoadLeftSideValue($Level, $Time)
  {
    $Result = array();
    $DbResult = $this->Database->select($this->Data['DataTable'], '*', '(Time < "'.
      TimeToMysqlDateTime($Time).'") AND (Measure='.$this->Data['Id'].') AND (Level='.$Level.') ORDER BY Time DESC LIMIT 1');
    if ($DbResult->num_rows > 0)
    {
      $Row = $DbResult->fetch_assoc();
      $Row['Time'] = MysqlDateTimeToTime($Row['Time']);
      return array($Row);
    } else
    {
      //$Time = $Values[0]['Time'] - 60;
      //array_unshift($Values, array('Time' => $Time, 'Min' => 0, 'Avg' => 0, 'Max' => 0, 'Continuity' => 0));
      if ($this->Debug) echo($this->TimeSegment($this->Data['Period'], $Level));
      $Result[] = array('Time' => ($Time - $this->TimeSegment($this->Data['Period'], $Level)), 'Min' => 0, 'Avg' => 0, 'Max' => 0, 'Continuity' => 0);

      $DbResult = $this->Database->select($this->Data['DataTable'], '*', 'Time > "'.TimeToMysqlDateTime($Time).'" AND Measure='.$this->Data['Id'].' AND Level='.$Level.' ORDER BY Time ASC LIMIT 1');
      if ($DbResult->num_rows > 0)
      {
        $Row = $DbResult->fetch_assoc();
        array_push($Result, array('Time' => (MysqlDateTimeToTime($Row['Time']) - 10), 'Min' => 0, 'Avg' => 0, 'Max' => 0, 'Continuity' => 0));
      }
      return $Result;
    }
  }

  function GetValues($TimeFrom, $TimeTo, $Level)
  {
    if ($this->Debug) echo('TimeFrom: '.$TimeFrom.'('.TimeToMysqlDateTime($TimeFrom).')<br>');
    if ($this->Debug) echo('TimeTo: '.$TimeTo.'('.TimeToMysqlDateTime($TimeTo).')<br>');

    //$AbsoluteTime = GetTimeRange($MeasureId);

    //  if (($TimeFrom > $AbsoluteLeftTime) and ($TimeStart < $AbsoluteRightTime) and
    //    ($TimeTo > $AbsoluteLeftTime) and ($TimeTo < $AbsoluteRightTime))
    //  {

    // Load values in time range
    $Result = $this->Database->select($this->Data['DataTable'], 'Time, Min, Avg, Max, Continuity', '(Time > "'.
      TimeToMysqlDateTime($TimeFrom).'") AND (Time < "'.
      TimeToMysqlDateTime($TimeTo).'") AND (Measure='.
      $this->Data['Id'].') AND (Level='.$Level.') ORDER BY Time');
    //  echo($Level.' '.TimeToMysqlDateTime($TimeFrom).' '.TimeToMysqlDateTime($TimeTo));
    $Values = array();
    //  echo(DB_NumRows());
    //  $III = 0;
    while ($Row = $Result->fetch_assoc())
    {
      //    echo($III.' '.$Row['Time'].' '.memory_get_usage().',');
      //    $III++;
      $Values[] = array('Time' => MysqlDateTimeToTime($Row['Time']), 'Min' => $Row['Min'],
        'Avg' => $Row['Avg'], 'Max' => $Row['Max'], 'Continuity' => $Row['Continuity']);
    }
    // array_pop($Values);
    if ($this->Debug) echo('Item count: '.count($Values));

    $Points = array();
    if (count($Values) > 0)
    {
      $Values = array_merge($this->LoadLeftSideValue($Level, $TimeFrom), $Values, $this->LoadRightSideValue($Level, $TimeTo));
      $StartIndex = 0;
      $Points = array();
      if ($this->Debug) print_r($Values);
      for ($I = 0; $I < $this->DivisionCount; $I++)
      {
        $TimeStart = $TimeFrom + (($TimeTo - $TimeFrom) / $this->DivisionCount) * $I;
        $TimeEnd = $TimeFrom + (($TimeTo - $TimeFrom) / $this->DivisionCount) * ($I + 1);
        if ($this->Debug) echo('TimeEnd '.$I.': '.$TimeEnd.'('.TimeToMysqlDateTime($TimeEnd).')<br>');

        $EndIndex = $StartIndex;
        while (($Values[$EndIndex]['Time'] < $TimeEnd) and ($EndIndex < count($Values))) $EndIndex = $EndIndex + 1;
        //while (($Values[$EndIndex]['Time'] < $TimeEnd)) $EndIndex = $EndIndex + 1;
        $SubValues = array_slice($Values, $StartIndex, $EndIndex - $StartIndex + 1);
        $Points[] = $this->ComputeOneValue($TimeStart, $TimeEnd, $SubValues, $Level);
        $StartIndex = $EndIndex - 1;
      }
      if ($this->Debug) print_r($Points);
    } else $Points[] = array('Min' => 0, 'Avg' => 0, 'Max' => 0);
    return $Points;
  }

  function RebuildMeasureCache()
  {
    echo('Veličina '.$this->Data['Name']."<br>\n");
    if ($this->Data['Continuity'] == 0) $this->Data['ContinuityEnabled'] = 0;  // non continuous
      else $this->Data['ContinuityEnabled'] = 2;    // continuous graph

    // Clear previous items
    $DbResult = $this->Database->select($this->Data['DataTable'], 'COUNT(*)', 'Level > 0 AND Measure='.$this->Data['Id']);
    $Row = $DbResult->fetch_row();
    echo("Mazu starou cache (".$Row[0]." polozek)...");
    $this->Database->delete($this->Data['DataTable'], 'Level > 0 AND Measure='.$this->Data['Id']);
    echo("<br>\n");

    for ($Level = 1; $Level <= $this->MaxLevel; $Level++)
    {
      echo('Uroven '.$Level."<br>\n");
      $TimeRange = $this->GetTimeRange($Level - 1);
      $TimeSegment = $this->TimeSegment($this->Data['Period'], $Level);
      $StartTime = $this->AlignTime($TimeRange['Left'], $TimeSegment) - $TimeSegment;
      $EndTime = $this->AlignTime($TimeRange['Right'], $TimeSegment);
      $BurstCount = 500;
      echo('For 0 to '.round(($EndTime - $StartTime) / $TimeSegment / $BurstCount)."<br>\n");
      for ($I = 0; $I <= round(($EndTime - $StartTime) / $TimeSegment / $BurstCount); $I++)
      {
        echo($I.' ');
        $StartTime2 = $StartTime + $I * $BurstCount * $TimeSegment;
        $EndTime2 = $StartTime + ($I + 1) * $BurstCount * $TimeSegment;
        $Values = array();
        $DbResult = $this->Database->select($this->Data['DataTable'], '*', 'Time > "'.
          TimeToMysqlDateTime($StartTime2).'" AND Time < "'.TimeToMysqlDateTime($EndTime2).'" AND Measure='.$this->Data['Id'].' AND Level='.($Level - 1).' ORDER BY Time');
        while ($Row = $DbResult->fetch_assoc())
        {
          $Row['Time'] = MysqlDateTimeToTime($Row['Time']);
          $Values[] = $Row;
        }

        if (count($Values) > 0)
        {
          $Values = array_merge($this->LoadLeftSideValue($Level - 1, $StartTime2),
          $Values, $this->LoadRightSideValue($Level - 1, $this->Data, $EndTime2));

          $StartIndex = 0;
          for ($B = 0; $B < $BurstCount; $B++)
          {
            echo('.');
            $StartTime3 = $StartTime2 + (($EndTime2 - $StartTime2) / $BurstCount) * $B;
            $EndTime3 = $StartTime2 + (($EndTime2 - $StartTime2) / $BurstCount) * ($B + 1);

            $EndIndex = $StartIndex;
            while ($Values[$EndIndex]['Time'] < $EndTime3) $EndIndex = $EndIndex + 1;
            $SubValues = array_slice($Values, $StartIndex, $EndIndex - $StartIndex + 1);
            if (count($SubValues) > 2)
            {
              $Point = $this->ComputeOneValue($StartTime3, $EndTime3, $SubValues, $Level);
              $Continuity = $SubValues[1]['Continuity'];
              $this->Database->insert($this->Data['DataTable'], array('Level' => $Level,
                'Measure' => $this->Data['Id'], 'Min' => $Point['Min'], 'Avg' => $Point['avg'],
                'max' => $Point['Max'], 'Continuity' => $Continuity, 'Time' =>
                TimeToMysqlDateTime($StartTime3 + ($EndTime3 - $StartTime3) / 2)));
            }
            $StartIndex = $EndIndex - 1;
          }
        }
        // Load values in time range
        //array_pop($NextValues);
      }
      echo("Uroven dokoncena<br>\n");
      $DbResult = $this->Database->select($this->Data['DataTable'], 'COUNT(*)', 'Level='.$Level.' AND Measure='.$this->Data['Id']);
      $Row = $DbResult->fetch_row();
      echo("Vloženo ".$Row[0]." položek.<br>\n");
    }
  }

  function RebuildAllMeasuresCache()
  {
    // echo("Vytvarim novou cache...\n");
    // Load measures
    $Measures = array();
    $Result = $this->Database->select('Measure', '*');
    while ($Row = $Result->fetch_assoc())
    {
      $Measure = new Measure($this->System);
      $Measure->Load($Row['Id']);
    }

    foreach ($Measures as $Measure)
    {
      $Measure->RebuildMeasureCache();
      echo('Velicina dokoncena<br>');
    }
  }

  function InitMeasureDataTable()
  {
    $this->Database->query('CREATE TABLE `Data'.$this->Data['Name'].'` (
`Time` TIMESTAMP NOT NULL ,
`Avg` '.$this->Data['DataType'].' NOT NULL ,
`Continuity` BOOL NOT NULL
) ENGINE = MYISAM ;');

    $this->Database->query('CREATE TABLE `Data'.$this->Data['Name'].'Cache` (
`Time` TIMESTAMP NOT NULL ,
`Level` TINYINT NOT NULL ,
`Min` '.$this->Data['DataType'].' NOT NULL ,
`Avg` '.$this->Data['DataType'].' NOT NULL ,
`Max` '.$this->Data['DataType'].' NOT NULL ,
`Continuity` BOOL NOT NULL
) ENGINE = MYISAM ;');
  }
}
