<?php

class SystemInfoHelper
{

  public static function getUserNameById($id)
  {
    $smbtid = $id;
    if ($smbtid === null)
      return t ( 'Unknown' );
    if ($smbtid == 0)
      return t ( 'Event Server' );
    $sbmt = User::findById ( $id );
    if ($sbmt == null)
      return t ( 'Unknown' );
    return $sbmt->getFullName ();
  }

  public static function getUserCoolName($id)
  {
    if (user ()->checkAccess ( 'user_view' ) && $id)
      return '<a href="' . url ( 'user/' . $id ) . '">' . self::getUserNameById ( $id ) . '</a>';
    else
      return self::getUserNameById ( $id );
  }

  public static function getNotificationSettingFilter(NotificationSetting $setting)
  {
    $html = "";
    if ($setting != null)
    {
      switch ($setting->object_table)
      {
        case NotificationSetting::OBJECT_TABLE_EVENT_REPORTING :
          switch ($setting->filter_type)
          {
            case NotificationSetting::FILTER_TYPE_ANY :
              break;
            case NotificationSetting::FILTER_TYPE_BLACKLIST :
              break;
            case NotificationSetting::FILTER_TYPE_BLACKLIST_ON_LIST :
              $list = PlateList::findByCode ( $setting->filter );
              if ($list != null)
              {
                $html = $list->getListTitle ();
                if ($list->userHasAccessCheckAll ())
                  $html = '<a href="' . url ( 'plateAuthorization/list', array (
                      'plateListId' => $list->id 
                  ) ) . '">' . $html . '</a>';
              }
              else
              {
                $html = t ( 'Not found' );
                $html = "<span class=\"color-red\" title=\"$setting->filter\">$html</span>";
              }
              break;
            case NotificationSetting::FILTER_TYPE_BLACKLIST_ON_PLATE :
              if (isEmpty ( $setting->filter ))
              {
                $html = t ( 'Empty' );
                $html = "<span class=\"color-red\" >$html</span>";
              }
              else
              {
                $html = "<span class=\"color-blue\" >$setting->filter</span>";
              }
              break;
            default :
              $html = $html . t ( 'Unknown' );
              break;
          }
          
          break;
        default :
          $html = t ( 'Unknown' );
          break;
      }
    }
    return $html;
  }

  public static function getNotificationSettingEndpointType(NotificationSetting $setting)
  {
    $html = "";
    if ($setting != null)
    {
      $typeLabel = t ( 'Endpoint Type' ) . ": " . NotificationSettingController::getEndpointTypesArray ( $setting->endpoint_type );
      switch ($setting->endpoint_type)
      {
        case NotificationSetting::ENDPOINT_TYPE_WEB :
          $html = "<span class=\"icon-globe\" title=\"$typeLabel\"></span>";
          break;
        case NotificationSetting::ENDPOINT_TYPE_MAIL :
          $html = "<span class=\"icon-envelope-alt\" title=\"$typeLabel\"></span>";
          break;
        default :
          $typeLabel = t ( 'Endpoint Type' ) . ": " . t ( 'Unknown' );
          $html = "<span class=\"icon-question\" title=\"$typeLabel\"></span>";
          break;
      }
    }
    return $html;
  }

  public static function getNotificationSettingTarget(NotificationSetting $setting)
  {
    $html = "";
    if ($setting != null)
    {
      if ($setting->target_type == NotificationSetting::TARGET_TYPE_USER)
      {
        $target = User::findById ( $setting->target_id );
        if ($target != null)
        {
          $html = $target->getFullName ();
          if (user ()->checkAccess ( 'manage_users' ))
            $html = "<a href=\"" . url ( 'user/view', array (
                'id' => $target->id 
            ) ) . "\">$html</a>";
        }
        else
        {
          $html = '<span class="color-red">' . t ( 'Not found' ) . '</span>';
        }
      }
      if ($setting->target_type == NotificationSetting::TARGET_TYPE_BROADCAST)
      {
        $html = t ( "Broadcast" );
      }
    }
    return $html;
  }

  public static function getNotificationStatus(Notification $notification)
  {
    $html = "";
    if ($notification != null)
    {
      $html = self::getNotificationStatusByString ( $notification->status );
    }
    return $html;
  }

  public static function getNotificationStatusByString($status)
  {
    $html = "";
    switch ($status)
    {
      case Notification::STATUS_DISMISSED :
        $html = t ( 'Dismissed' );
        break;
      case Notification::STATUS_DUMPED :
        $html = t ( 'Dumped' );
        break;
      case Notification::STATUS_LOADING :
        $html = t ( 'Loading' );
        break;
      case Notification::STATUS_SHOWN :
        $html = t ( 'Shown' );
        break;
      case Notification::STATUS_UNREAD :
        $html = t ( 'Unread' );
        break;
      default :
        $html = t ( 'Unknown' );
        break;
    }
    return $html;
  }

  public static function getNotificationObjectLink(Notification $notification)
  {
    $html = "";
    
    if ($notification != null)
    {
      $setting = $notification->setting;
      if ($setting != null)
      {
        switch ($notification->setting->object_table)
        {
          case NotificationSetting::OBJECT_TABLE_EVENT_REPORTING :
            $alert = Alert::model ()->findByPk ( $notification->object_id );
            if ($alert == null)
            {
              $html = "ID: $notification->setting_id";
            }
            else
            {
              $html = $alert->description;
              if (user ()->checkAccess ( 'view_alerts' ))
                $html = "<a href=\"" . url ( 'alert/view', array (
                    'id' => $alert->id 
                ) ) . "\">$html</a>";
            }
            $html = "$html (" . t ( 'Alert' ) . ")";
            break;
          default :
            $html = "ID: $notification->setting_id";
            break;
        }
      }
      else
      {
        $html = "ID: $notification->setting_id";
      }
    }
    return $html;
  }

  public static function getNotificationSettingLink(NotificationSetting $setting)
  {
    $html = "";
    if ($setting != null)
    {
      $html = $setting->description;
      if (user ()->checkAccess ( 'notification_setting_management' ))
        $html = "<a href=\"" . url ( 'notificationSetting/view', array (
            'id' => $setting->id 
        ) ) . "\">$html</a>";
    }
    return $html;
  }

  public static function getNotificationHtml(NotificationSetting $s, Notification $n)
  {
    $html = "";
    $timestamp = $n->epoch;
    
    if ($s->object_table == NotificationSetting::OBJECT_TABLE_EVENT_REPORTING)
    {
      switch ($s->filter_type)
      {
        case NotificationSetting::FILTER_TYPE_ANY :
          $alert = Alert::model ()->findByPk ( $n->object_id );
          $html = "<a href=\"" . url ( 'alert/view', array (
              'id' => $alert->id 
          ) ) . "\">$alert->description</a>";
          $timestamp = $alert->epoch;
          break;
        case NotificationSetting::FILTER_TYPE_BLACKLIST :
          $alert = Alert::model ()->findByPk ( $n->object_id );
          $html = "<a href=\"" . url ( 'alert/view', array (
              'id' => $alert->id 
          ) ) . "\">$alert->description</a>";
          $timestamp = $alert->epoch;
          break;
        case NotificationSetting::FILTER_TYPE_BLACKLIST_ON_LIST :
          $alert = Alert::model ()->findByPk ( $n->object_id );
          $html = "<a href=\"" . url ( 'alert/view', array (
              'id' => $alert->id 
          ) ) . "\">$alert->description</a>";
          $timestamp = $alert->epoch;
          break;
        case NotificationSetting::FILTER_TYPE_BLACKLIST_ON_PLATE :
          $alert = Alert::model ()->findByPk ( $n->object_id );
          $html = "<a href=\"" . url ( 'alert/view', array (
              'id' => $alert->id 
          ) ) . "\">$alert->description</a>";
          $timestamp = $alert->epoch;
          break;
        default :
          break;
      }
    }
    
    return array (
        'timestamp' => "" . DateHelper::ensureObjectEx ( $timestamp ),
        'content' => $html,
        'view_url' => url ( 'notification/view', array (
            'id' => $n->id 
        ) ),
        'dismiss_url' => url ( 'notification/dismiss', array (
            'id' => $n->id 
        ) ) 
    );
  }

  public static function getColorSetHtml(Event $data, $colorsCount = 3)
  {
    $html = null;
    if ($data != null)
    {
      $colorSet = $data->colorSet;
      if (isset ( $colorSet ) && $colorSet->computed)
      {
        $colors = $colorSet->getColorsArray ( $colorsCount );
        if ($colors != null)
        {
          $html .= "<div class=\"color-set\">";
          foreach ( $colors as $color )
            $html .= " <span style=\"background-color: $color\" data-toggle=\"tooltip\" title=\"$color\"></span>";
          $html .= "</div>";
        }
        // $this->renderPartial("/shared/_colorSet", array("colors" => $colorSet->getColorsArray($colorsCount)), true);
      }
    }
    return $html;
  }

  /**
   *
   * @param Event $event          
   * @return string HTML
   */
  public static function getEventAlertIcon(Event $event)
  {
    $icon = AlertPresenter::getProperty ( $event->alert, "getLevelIcon" );
    $name = AlertPresenter::getProperty ( $event->alert, "getHtmlEventDescription" );
    return "<a class=\"tooltipbox\">$icon<span>$name</span></a>";
  }

  /**
   *
   * @param Event $event          
   */
  public static function getEventSearchStatus(Event $event)
  {
    $status = SystemInfoHelper::getEventStatus ( $event );
    $button = SystemInfoHelper::getSingleEventAction ( $event );
    return "$status $button";
  }

  /**
   *
   * @param Event $event          
   */
  public static function getEventStatus(Event $event)
  {
    $result = "";
    
    if ($event->isNew ())
      $result = '<div class="icon-check-empty" title="' . t ( "New" ) . '"></div>';
    
    if ($event->isExamined ())
      $result = '<div class="icon-eye-open" title="' . t ( "Examined" ) . '"></div>';
    
    if ($event->isValidated ())
      $result = '<div class="icon-check" title="' . t ( "Validated" ) . '"></div>';
    
    if ($event->isExported ())
      $result = '<div class="icon-signout" title="' . t ( "Exported" ) . '"></div>';
    
    $behaviors = array ();
    $behaviors ['new'] = array ();
    $behaviors ['approved'] = array ();
    $behaviors ['pending'] = array ();
    $behaviors ['invalid'] = array ();
    foreach ( $event->eventBehaviors as $beh )
    {
      if ($beh->isNew ())
        $behaviors ['new'] [] = $beh;
      if ($beh->isApproved ())
        $behaviors ['approved'] [] = $beh;
      if ($beh->isPending ())
        $behaviors ['pending'] [] = $beh;
      if ($beh->isInvalid ())
        $behaviors ['invalid'] [] = $beh;
    }
    
    $stats = array ();
    if (count ( $behaviors ['new'] ) > 0)
    {
      $stats [] = '<b title="' . t ( 'New' ) . '">' . count ( $behaviors ['new'] ) . '</b>';
    }
    if (count ( $behaviors ['approved'] ) > 0)
    {
      $stats [] = '<b><font title="' . t ( 'Approved' ) . '" color="#51a351">' . count ( $behaviors ['approved'] ) . '</font></b>';
    }
    if (count ( $behaviors ['pending'] ) > 0)
    {
      $stats [] = '<b><font title="' . t ( 'Pending' ) . '" color="#f89406">' . count ( $behaviors ['pending'] ) . '</font></b>';
    }
    if (count ( $behaviors ['invalid'] ) > 0)
    {
      $stats [] = '<b><font title="' . t ( 'Invalid' ) . '" color="#bd362f">' . count ( $behaviors ['invalid'] ) . '</font></b>';
    }
    
    if (count ( $stats ) > 0)
      $stats = ' ' . implode ( '/', $stats );
    else
      $stats = '';
    return $result . $stats;
  }

  /**
   *
   * @param Event $event          
   */
  public static function getSingleEventAction(Event $event, $returnUrl = null)
  {
    $view = '<a rel="tooltip" target="_blank" data-original-title="' . t ( 'View' ) . '" href="' . url ( "event/view", array (
        'id' => $event->ID 
    ) ) . '"><div class="icon-zoom-in"></div></a>';
    $update = '';
    $delete = '';
    
    $service = $event->service;
    if ($service == null)
      $update = "";
    elseif (! $service->isReadyForEvaluation ())
      $update = "";
    elseif (isset ( $service->assignedOperator ) && ! $service->isAssignedTo ( user ()->id ))
      $update = ' <div class="icon-user" title="' . t ( 'Taken in charge by' ) . ' ' . $service->assignedOperator->fullName . '"></div>';
    elseif (! isset ( $service->assignedOperator ))
      $update = "";
    elseif ($event->isExported ())
      $update = "";
    elseif ($service->isAssignedTo ( user ()->id ) && ! $event->isExported ())
      $update = ' <a rel="tooltip" target="_blank" data-original-title="' . t ( 'Update' ) . '" href="' . url ( 'event/edit', array (
          'id' => $event->ID 
      ) ) . '" class="icon-pencil"></a>';
    
    if (paramdeep ( 'events', 'deleteEnabled' ) && user ()->checkAccess ( 'event_delete' ))
      $delete = ' <a rel="tooltip" data-original-title="' . t ( 'Delete' ) . '" href="' . url ( 'event/delete', array (
          'id' => $event->ID,
          'returnUrl' => $returnUrl 
      ) ) . '" class="icon-trash" onclick="return confirm(\'' . t ( 'Confirm?' ) . " " . t ( 'WARNING: it cannot be undone!' ) . '\');"></a>';
    
    return $view . $update . $delete;
  }

  public static function getRecentTimeLabel($time, $maxElapsed, $cfrTime = null)
  {
    $time = DateHelper::ensureObjectEx ( $time );
    $cfrTime = DateHelper::ensureObjectEx ( $cfrTime );
    $result = $cfrTime->toDateTime ()
      ->diff ( $time->toDateTime () );
    $old = $result->format ( "%Y-%M-%D %H:%I:%S" ) > $maxElapsed;
    if ($old)
      return "<font color=\"red\">$time</font>";
    else
      return "<font color=\"green\">$time</font>";
  }

  public static function getFullSwitchButtonLabel($ctrl, $act, $id, $value, $labelPos = 'Yes', $labelNeg = 'No', $colorPos = 'green', $colorNeg = 'red', $ret = null, $class = 'icon-off', $auth = null, $lnktext = '')
  {
    if (isEmpty ( $auth ))
      $isauth = true;
    else
      $isauth = user ()->checkAccess ( $auth );
    
    if ($isauth)
      $link = SystemInfoHelper::getSwitchLink ( $ctrl, $act, $id, $ret, $class, $lnktext );
    $label = SystemInfoHelper::getPosNegLabel ( $value, $labelPos, $labelNeg, $colorPos, $colorNeg );
    return "$link $label";
  }

  public static function getSwitchLink($controller, $action, $id, $returnUrl = null, $class = 'icon-off', $text = '')
  {
    $params = array ();
    
    $params ['id'] = $id;
    if (! empty ( $returnUrl ))
      $params ['returnUrl'] = $returnUrl;
    
    return '<a class="' . $class . '" href="' . url ( "$controller/$action", $params ) . '">' . $text . '</a>';
  }

  public static function getPosNegLabel($value, $labelPos = 'Yes', $labelNeg = 'No', $colorPos = 'green', $colorNeg = 'red')
  {
    return "<font color=\"" . ($value ? $colorPos : $colorNeg) . "\"><i>" . ($value ? t ( $labelPos ) : t ( $labelNeg )) . "</i></font>";
  }

  public static function getPlateAuthGateCoolName($id, $type, $createLink = true, $embedInDiv = true, $highlightErrors = true)
  {
    if ($id == - 1)
      return t ( "All gates" );
    
    switch ($type)
    {
      case PlateAuthorization::GATEID_TYPE_GATE :
        return "[" . t ( 'Gate' ) . "] " . self::getGateCoolName ( $id, $createLink, $embedInDiv, $highlightErrors, false );
      case PlateAuthorization::GATEID_TYPE_GROUP :
        return "[" . t ( 'Group' ) . "] " . self::getGateGroupCoolName ( $id, $createLink, $embedInDiv, $highlightErrors );
      case PlateAuthorization::GATEID_TYPE_SET :
        return "[" . t ( 'Set' ) . "] " . self::getGateSetCoolName ( $id, $createLink, $embedInDiv, $highlightErrors );
    }
    return "[$type] $id";
  }

  public static function getGateCoolName($id, $createLink = true, $embedInDiv = true, $highlightErrors = true, $idIsGate = false)
  {
    if ($id == - 1)
    {
      $content = t ( "All gates" );
    }
    else
    {
      if ($idIsGate)
        $item = Gate::model ()->find ( 'Gate=:gt', array (
            ':gt' => $id 
        ) );
      else
        $item = Gate::model ()->findByPk ( $id );
      $content = $id;
      if ($item == null)
      {
        $content = t ( "Gate not found" );
        if ($highlightErrors)
          $content = "<font color=\"red\"><i title=\"$id\">$content!</i></font>";
      }
      else
      {
        $content = $item->GateName;
        if ($createLink && user ()->checkAccess ( 'manage_gates' ))
        {
          $url = url ( 'gate/' . $item->ID );
          $content = "<a target=\"_blank\" href=\"$url\">$content</a>";
        }
      }
    }
    
    return $embedInDiv ? "<span title=\"$item->Gate\">$content</span>" : $content;
  }

  public static function getGateGroupCoolName($id, $createLink = true, $embedInDiv = true, $highlightErrors = true)
  {
    if ($id == - 1)
    {
      $content = t ( "None" );
    }
    else
    {
      $item = GateGroup::model ()->findByPk ( $id );
      $content = $id;
      if ($item == null)
      {
        $content = t ( "Gate group not found" );
        if ($highlightErrors)
          $content = "<font color=\"red\"><i title=\"$id\">$content!</i></font>";
      }
      else
      {
        $content = $item->name;
        if ($createLink && user ()->checkAccess ( 'manage_gates' ))
        {
          $url = url ( 'gateGroup/' . $id );
          $content = "<a target=\"_blank\" href=\"$url\">$content</a>";
        }
      }
    }
    return $embedInDiv ? "<span title=\"$item->name\">$content</span>" : $content;
  }

  public static function getGateSetCoolName($id, $createLink = true, $embedInDiv = true, $highlightErrors = true)
  {
    if ($id == - 1)
    {
      $content = t ( "None" );
    }
    else
    {
      $item = GateSet::model ()->findByPk ( $id );
      $content = $id;
      if ($item == null)
      {
        $content = t ( "Gate set not found" );
        if ($highlightErrors)
          $content = "<font color=\"red\"><i title=\"$id\">$content!</i></font>";
      }
      else
      {
        $content = $item->name;
        if ($createLink && user ()->checkAccess ( 'manage_gates' ))
        {
          $url = url ( 'gatesets/' . $id );
          $content = "<a target=\"_blank\" href=\"$url\">$content</a>";
        }
      }
    }
    return $embedInDiv ? "<span title=\"$item->name\">$content</span>" : $content;
  }

  public static function getTimeScheduleCoolName($id, $createLink = true, $highlightErrors = true)
  {
    if ($id == - 1)
    {
      $content = t ( "Always" );
    }
    else
    {
      $item = TimeSchedule::model ()->findByPk ( $id );
      $content = $id;
      if ($item == null)
      {
        $content = t ( "Time Schedule not found" );
        if ($highlightErrors)
          $content = "<font color=\"red\"><i title=\"$id\">$content!</i></font>";
      }
      else
      {
        $content = $item->Descrizione;
        if ($createLink && user ()->checkAccess ( 'manage_time_schedule' ))
        {
          $url = url ( 'timeSchedule/' . $id );
          $content = "<a target=\"_blank\" href=\"$url\">$content</a>";
        }
      }
    }
    return $content;
  }

  public static function getTransitoCoolName($transito)
  {
    if ($transito != "Limitato")
      return "<font color=\"green\">" . t ( "Free access" ) . "</font>";
    else
      return "<font color=\"red\">" . t ( "Limited access" ) . "</font>";
  }

  public static function getBehaviorCoolName($id, $createLink = true, $highlightErrors = true)
  {
    $item = Behavior::model ()->findByPk ( $id );
    $content = $id;
    if ($item == null)
    {
      $content = t ( "Behavior not found" );
      if ($highlightErrors)
        $content = "<font color=\"red\"><i title=\"$id\">$content!</i></font>";
    }
    else
    {
      $content = t ( $item->name );
      if ($createLink && user ()->checkAccess ( 'behavior_manage' ))
      {
        $url = url ( 'behavior/' . $id );
        $content = "<a title=\"$id\" target=\"_blank\" href=\"$url\">$content</a>";
      }
    }
    return $content;
  }

  public static function getTrafficEventIcon($value)
  {
    $value = ( string ) $value;
    switch ($value)
    {
      case "0" :
        return '<div class="icon-remove alarm info-icon" style="color: red;" title="' . t ( 'Disabled' ) . '"></div>';
        break;
      case "1" :
        return '<div class="icon-info-sign alarm info-icon" title="' . t ( 'Info' ) . '"></div>';
        break;
      case "info" :
        return '<div class="icon-info-sign alarm info-icon" title="' . t ( 'Info' ) . '"></div>';
        break;
      case "2" :
        return '<div class="icon-warning-sign alarm warning-icon" title="' . t ( 'Warning' ) . '"></div>';
        break;
      case "warning" :
        return '<div class="icon-warning-sign alarm warning-icon" title="' . t ( 'Warning' ) . '"></div>';
        break;
      case "3" :
        return '<div class="icon-exclamation-sign alarm alarm-icon" title="' . t ( 'Alarm' ) . '"></div>';
        break;
      case "alarm" :
        return '<div class="icon-exclamation-sign alarm alarm-icon" title="' . t ( 'Alarm' ) . '"></div>';
        break;
      default :
        return '<i>' . t ( 'Unknown' ) . '</i>';
        break;
    }
  }

  public static function trafficEventSelector($id, $currentLevel, $ctrl, $action, $levelField, $returnUrl = null)
  {
    $html = "";
    foreach ( range ( 0, 3 ) as $level )
    {
      $icon = self::getTrafficEventIcon ( $level );
      $link = '<a href="' . url ( "$ctrl/$action", array_set_if ( array (
          'id' => $id,
          $levelField => $level 
      ), ! empty ( $returnUrl ), "returnUrl", $returnUrl ) ) . '">' . $icon . '</a>';
      if ($currentLevel == $level)
        $link = "<div style=\"border: thin; border-color: blue; border-style: solid; border-radius: 3px; padding: 2px; display: inline;\">$link</div>";
      else
        $link = "<div style=\"padding: 2px; display: inline;\">$link</div>";
      $html .= $link;
    }
    return $html;
  }
}
