<?php
namespace App\Modules\Mattermost;

use Illuminate\Support\Facades\Auth;
use App\Models\User;
use Illuminate\Support\Facades\Input;
use Status;
use App\Modules\Clients\Site;
use App\Modules\Clients\Client;
use App\Modules\Clients\Customer;

class MattermostHelper
{
  /*
  This class contains helper functions for the mattermost controllers.
  */

  protected $defaultSettings = array (
    'clientId'      => 53, // computer assistance
    'clientName'    => 'Computer', // computer assistance
    'responseType'  => 'ephemeral', // mattermost response type - only to yourself
    'username' 			=> 'Seraph', // mattermost something
    'adminUserId'   => 1, // administrator
    'success'       => false,
    'searchType'    => 'open',
    'adminUserName' => 'admin', // administrator
  );

  protected $defaultBookingsData = array (
    'client'        => "",
    'client_name'   => "",
    'client_type'   => "client",
    'title'         => "",
    'type'          => "support",
    'problem'       => "",
    'site_id'       => 53, //comp assistance
    'site_user_id'  => 53, // Main User
    'severity_id'   => 2, // normal
  );

  protected $processedBookingsData = array (
    'client'        => "",
    'client_name'   => "",
    'client_type'   => "client",
    'title'         => "",
    'type'          => "support",
    'problem'       => "",
    'site_id'       => null,
    'site_user_id'  => 53,
    'severity_id'   => 2,
  );

  protected $markdownControls = array (
    'user'        => array ('char' => '@', 'length' => 1),
    'client'      => array ('char' => '#', 'length' => 1),
    'shouter'     => array ('char' => '>', 'length' => 1),
    'problem'     => array ('char' => '|', 'length' => 1),
  );

  protected $simpleMarkdownControls = array (
    'user'         => '@',
    'client'       => '#',
    'shouter'      => '>',
    'problem'      => '|',
  );

  protected $controls = [
    'user'        => false,
    'client'      => false,
    'title'       => false,
    'problem'     => false,
  ];

  function getAllDefaultSettings(){
    return $this->defaultSettings;
  }

  function getSingleDefaultSetting($key){
    return $this->defaultSettings[$key];
  }

  function getAllDefaultBookingsData(){
    return $this->defaultBookingsData;
  }

  function getSingleDefaultBookingsData($key){
    return $this->defaultBookingsData[$key];
  }

  /********************
  * functions below
  ********************/


  function sendResponse($message)	{
    $response = [
      'success'      	=> true,
      'response_type'	=> 'ephemeral',
      'username' 			=> 'Seraph',
      'text'         	=> $message
    ];
    return response()->json($response, ($response['success']) ? 200 : 400);
  }

  function sendEnhancedResponse($message , $successBool, $responseType)	{
    $response = [
      'success'      	=> $successBool,
      'response_type'	=> $responseType,
      'username' 			=> 'Seraph',
      'text'         	=> $message
    ];
    return response()->json($response, ($response['success']) ? 200 : 400);
  }

  function containsWord($str, $word)
  {
    return !!preg_match('#\b' . preg_quote($word, '#') . '\b#i', $str);
  }

  function checkAllCall($str) {
    $re = '/\s?(>all)\s?/'; //captures >all
    return !!preg_match($re, $str);
  }

  function checkMyCall($str) {
    $re = '/\s?(my)\s?/'; //captures >all
    return !!preg_match($re, $str);
  }

  function isMarkdownChar($char){

    foreach ($this->simpleMarkdownControls  as $control) {
      if($char == $control) {
        return true;
      }
    }
  }

  function isMarkdownControl($chars){
    foreach ($this->markdownControls  as $control) {

      if($chars == $control) {
        return true;
      }
      else {
        return false;
      }
    }
  }

  function beginsWithChar($char, $word){
    if($word[0] == $char && strlen($word) > 1) {
      return true;
    }
    else {
      return false;
    }
  }


  function removeArrowControls($text){
    $returnText = null;
    $words = array_filter(explode(" ", $text));

    foreach ($words as $word) {
      if ($word[0] != ">") {
        $returnText .= $word . " ";
      }
      else {
        continue;
      }
    }
    return trim($returnText);
  }

  function setResponseType($text){
    $all = null;
    $re = '/\s?(>all)\s?/'; //captures >all

    return !!preg_match($re, $text) ?  "in_channel" : $this->defaultSettings['responseType'];
  }


  function getName($char, $text) {

    $words = $this->getWords(" ", $text);

    foreach ($words as $word) {
      if ($this->beginsWithChar($char, $word)) {
      return substr($word, 1);
      }
      else {
        return false;
      }
    }
  }


  function setSearchType($request){
    if($request != ""){
      $my = $this->checkMyCall($request);
    }
    if($my) {
      return "my";
    }
    else {
      return $this->defaultSettings['searchType']; // open
    }
  }

  /**
  * get words - takes a string, breaks it into words based on the delimiter
  * @ params
  * $text - string to process
  * $char - delimiter
  * array filter removes empty array elements ususally caused if space is used asa delimter and there are 2 spaces together in a string`
  * @ returns an array of strings*/
  function getWords($char, $text){
    return  array_filter(explode($char, $text));
  }


  /**
  * processInput - if there is text after the salsh command prcess it
  *	'user'        => false,
  *	'client'      => false,
  *	'title'       => false,
  *	'problem'     => false,
  *
  * the values built up here, control most aspects of the job booking in process
  * @ param`Reqest $request input
  * @ return array of values
  */
  function processInput($text){

    $controlsFound = $this->controls;

    // user and client section
    $wordsToProcess = $this->getWords(" ", $text);

    foreach ($wordsToProcess as $word) {

      if ($controlsFound['user'] == false || $controlsFound['user'] == null)
      $controlsFound['user'] = $this->getMeTheUser($word);

      if ($controlsFound['client'] == false || $controlsFound['client'] == null)
      $controlsFound['client'] = $this->getMeTheClient($word);

      // $controlsFound['shouter'] = $this->isThisTheShouter($word);
      // to implement?
    }

    // title and problem section
    if ($controlsFound['problem'] == false || $controlsFound['problem'] == null)
    $controlsFound['problem'] = $this->getMeTheProblem($text);

    if ($controlsFound['title'] == false || $controlsFound['title'] == null)
    $controlsFound['title'] = $this->getMeTheTitle($text);

    return $controlsFound;
  }

  function getMeTheUser($word) {
    if (strlen($word) > 2) {
      if($word[0] == $this->simpleMarkdownControls['user']) {
        return substr($word, 1);
      }
      else {
        return false;
      }
    }
  }

  function getMeTheClient($word) {

    if (strlen($word) > 2) {

      if($word[0] == $this->simpleMarkdownControls['client']) {
        return substr($word, 1);
      }
      else {
        return false;
      }
    }
  }

  function getMeTheProblem($text) {

    $idx = false;
    $wordChoice = "";
    $problem = false;

    $idx = strpos($text, "|");

    $wordChoice = $idx ? explode("|", $text)[1] : $text; // 2nd index ensures getting string after || if present

    $words = $this->getWords(" ", $wordChoice);

    foreach ($words as $word) {
      if (!$this->isMarkdownChar($word[0])) {
        $problem .= $word . " ";
      }
    }

    $idx = strpos($problem, "|");

    if ($idx === 0  || $idx){
      $problem = substr($problem, $idx + 1); // remove || if left over by problem/title creation
    }
    ($problem);
    return trim($problem);
  }

  function getMeTheTitle($text) {

    $idx = false;
    $wordChoice = "";
    $words ="";
    $title = false;

    $idx = strpos($text, "|");

    $wordChoice = $idx ? explode("|", $text)[0] : $text;

    $words = $this->getWords(" ", $wordChoice);

    foreach ($words as $word) {
      if (!$this->isMarkdownChar($word[0])) {
        $title .= $word . " ";
      }
    }

    $idx = strpos($title, "|"); // remove || if left over by problem/title creation
    if ($idx === 0 || $idx){
      $title = substr($title, $idx + 1);
    }
    return trim($title);
  }

  function getRequestingUserName($request) {
    if ($request->input('user_name')) {
      return $request->input('user_name');
    }
    else {
      //no requesting username sent..
      return false;
    }
  }

  function loginAuthUser($request) {
    if ($request->input('user_name')) {
      $user =  User::query()->where('username','like', '%' . $request->input('user_name') . '%')->first();
      if($user)	{
        Auth::login($user);
      }
      else {
        //Failed to find user, fall back to admin
        Auth::login(User::find($this->getSingleDefaultSetting("adminUserId")));
      }
    }
    else {
      // no user logged in on mattermost - use admin
      Auth::login(User::find($this->getSingleDefaultSetting("adminUserId")));
    }
  }


  function getClientData($clientName) {

    if($clientName){
      $client = $this->getNamedClientFromDatabase($clientName);
      if($client) {
        return array(
          'client' => $client
        );
      }
      else {
        return array(
          'error' => " | Client \"". $clientName."\" not found - booked as Computer Assistance! ",
          'client' => $this->getNamedClientFromDatabase($this->defaultSettings['clientName'])
        );
      }
    }
    else {
      return array(
        'error' => " | Client not specified - booked as Computer Assistance! ",
        'client' => $this->getNamedClientFromDatabase($this->defaultSettings['clientName'])
      );
    }
  }

  function getNamedClientFromDatabase($clientName) {
    return Client::query()->where('name','like', '%' . $clientName . '%')->first() ?  Client::query()->where('name','like', '%' . $clientName . '%')->with('sites.users')->first() : false;
  }

  function clientSearch ($clientName) {
    return Client::query()->leftJoin('sites', 'sites.client_id', '=', 'clients.id')
    ->where('clients.name', 'like', '%' . $clientName .'%')
    ->select('clients.name','sites.primary_phone', 'sites.name as site_name')
    ->orderBy('clients.name', 'asc')->get();
  }

  function getAllClients() {
      return Client::query()->leftJoin('sites', 'sites.client_id', '=', 'clients.id')
      ->select('clients.name','primary_phone')
      ->groupBy('clients.name')
      ->orderBy('clients.name', 'asc')->get();
  }

  function getUserData($userName) {

    if ($userName) {
      $user = $this->getUserFromDatabase($userName);
      if ($user) {
        return array(
          'user' => $user
        );
      }
      else {
        return array(
          'error' => " | User \"". $userName."\" not found - job added to queue! ",
          'user' => $user
        );
      }
    }
    else {
      return array(
        'error' => " | No user specified - job added to queue! ",
        'user' => false
      );
    }
  }

  function getUser($text) {

    $userName = $this->getName('@', $text);

    if ($userName) {
      $user = $this->getUserFromDatabase($userName);
      if ($user) {
        return $user;
      }
      else {
        return false;
      }
    }
    else {
      return false;
    }
  }

  function getAuthUserFromDatabase($request) {
    return $request->input('user_name') ? User::query()->where('username','like', '%' . $request->input('user_name') . '%')->where('active', 1)->first() : false; // user not found
  }

  function getUserFromDatabase($userName) {
    return User::query()->where('username','like', '%' . $userName . '%')->where('active', 1)->first() ? User::query()->where('username','like', '%' . $userName . '%')->where('active', 1)->first() : false; // user not found
  }

  function getUserIdFromDatabase($userName) {
    return User::query()->where('username','like', '%' . $userName . '%')->where('active', 1)->first() ? User::query()->where('username','like', '%' . $userName . '%')->where('active', 1)->first()->id : false; // user not found
  }

  function getUserExtFromDatabase($request) {
    $userName = $this->getRequestingUserName($request);
    return User::query()->where('username','like', '%' . $userName . '%')->where('active', 1)->first() ? User::query()->where('username','like', '%' . $userName . '%')->where('active', 1)->first()->extension : false; // user not found
  }

  function getAllUsers() {
    return User::getActiveList();
  }

  function userSearch($text){
    return User::query()->where('username','like', '%' .$text . '%')
    ->where('active', 1)->orderBy('first_name', 'asc')->get();
  }


  function makeUsersTable($data) {

    $text = "";
    $tableHeader = "";

    if (property_exists($data, 'users')) {
      $users = $data->users;
    }

    if (property_exists($data, 'userExtension')){
      $userExtension = $data->userExtension;
    }
    else {
      $userExtension = false;
    }

    $totalActiveUsers = User::query()
    ->where('active', 1)
    ->count();

    if (property_exists($data,'searchTerm')) {
      $tableHeader = "### CA Users | Search \"" . $data->searchTerm . "\"";
    }
    else {
      $tableHeader = "### CA Users | All";
    }

    $text = $text . $tableHeader ;
    $text = $text ."

| Username | First | Last | Mobile | Ext | Email |
|:---------|:-------|:----|:----|:----|:----|
";

    foreach ($users as $user) {
      if ($user->mobile) {
        $phoneMobileUrl = $userExtension ? '[' . $user->mobile   . '](http://' . env('CLICKTOCALL_SERVER', 'localhost') . '/clicktocall/callandclose.php?num='.urlencode($user->mobile).'&ext='.urlencode($userExtension).')' : $user->mobile;
      }
      else {
        $phoneMobileUrl = "";
      }
      $phoneExtensionUrl = $userExtension ? '[' .$user->first_name . ' (' .$user->extension . ')](http://' . env('CLICKTOCALL_SERVER', 'localhost') . '/clicktocall/callandclose.php?num='.urlencode($user->extension).'&ext='.urlencode($userExtension).')' : $user->extension;
      $text = $text . "|" . $user->username. "|". $user->first_name. "|". $user->last_name. "|" . $phoneMobileUrl ."|" . "$phoneExtensionUrl|" . "[$user->email](mailto:$user->email)" . "|" . "\n";
    }
      $text = $text . "---";

    return $this->sendEnhancedResponse($text, true, $data->responseType);
  }

  // unused but a lot of time went into it - may be used in thee future
  function makeClientsTableNew($clients) {

    $text = "";
    $tableHeader = "";

    if(property_exists($clients, 'userExtension')) {
      $userExtension = $clients->userExtension;
    }
    else {
      $userExtension = false;
    }

    if(property_exists($clients, 'responseType')) {
      $responseType = $clients->responseType;
    }
    else {
      $responseType = $this->defaultSettings['responseType'];
    }

  	if(property_exists($clients,"searchTerm")) { // make table showing all clients
      $tableTitle = "### CA Users | Clients \"" . $clients->searchTerm . "\n";
      $tableColumns =
"| Name | Site | Location | Number |
|:-------|:-------|:-------|:-------|
";
      $tableHeader = $tableTitle . $tableColumns;
      $text = $text . $tableHeader;

      $clientName = $clients[0]->name;

      foreach ($clients[0]->sites as $client) {
        if ($client->primary_phone) {
          $phoneExtensionUrl = $userExtension ? '[' . $client->primary_phone . '](http://' . env('CLICKTOCALL_SERVER', 'localhost') . '/clicktocall/callandclose.php?num='.urlencode($client->primary_phone).'&ext='.urlencode($userExtension).')' : $client->primary_phone;
          $text = $text . "|" . $clientName . "|" . $client->name . "|". $client->address .", ". $client->address2 ."|" . $phoneExtensionUrl . "|" . "\n";
        }
        else {
          $phoneExtensionUrl = "";
        }
      }
    }
    else {

      $tableTitle = "### CA Clients | All \n";
      $tableColumns =
"| Name | Number |
|:-------|:-------|
";
      $tableHeader = $tableTitle . $tableColumns;
      $text = $text . $tableHeader;
      foreach ($clients as $client) {
        if ($client->primary_phone) {
          $phoneExtensionUrl = $userExtension ? '[' . $client->primary_phone . '](http://' . env('CLICKTOCALL_SERVER', 'localhost') . '/clicktocall/callandclose.php?num='.urlencode($client->primary_phone).'&ext='.urlencode($userExtension).')' : $client->primary_phone;
          $text = $text . "|" . $client->name . "|" . $phoneExtensionUrl . "|" . "\n";
        }
        else {
          $phoneExtensionUrl = "";
        }
      }
    }
    $text = $text . "---";

    return $this->sendEnhancedResponse($text, true, $responseType);
  }


  function makeClientsTable($clients) {
    $text = "";
    $tableHeader = "";
    if(property_exists($clients, 'userExtension')) {
      $userExtension = $clients->userExtension;
    }
    else {
      $userExtension = false;
    }
    if(property_exists($clients, 'responseType')) {
      $responseType = $clients->responseType;
    }
    else {
      $responseType = $this->defaultSettings['responseType'];
    }
  	if(property_exists($clients,"searchTerm")) { // make table showing all clients
      $tableTitle = "### CA Users | Clients \"" . $clients->searchTerm . "\"\n";
      $tableColumns =
"| Name | Site |Number |
|:-------|:-------|:-------|
";
      $tableHeader = $tableTitle . $tableColumns;
      $text = $text . $tableHeader;
      foreach ($clients as $client) {
        if ($client->primary_phone) {
          $phoneExtensionUrl = $userExtension ? '[' . $client->primary_phone . '](http://' . env('CLICKTOCALL_SERVER', 'localhost') . '/clicktocall/callandclose.php?num='.urlencode($client->primary_phone).'&ext='.urlencode($userExtension).')' : $client->primary_phone;
          $text = $text . "|" . $client->name . "|" . $client->site_name . "|" . $phoneExtensionUrl . "|" . "\n";
        }
        else {
          $phoneExtensionUrl = "";
        }
      }
    }
    else {
      $tableTitle = "### CA Clients | All \n";
      $tableColumns =
"| Name | Number |
|:-------|:-------|
";
      $tableHeader = $tableTitle . $tableColumns;
      $text = $text . $tableHeader;
      foreach ($clients as $client) {
        if ($client->primary_phone) {
          $phoneExtensionUrl = $userExtension ? '[' . $client->primary_phone . '](http://' . env('CLICKTOCALL_SERVER', 'localhost') . '/clicktocall/callandclose.php?num='.urlencode($client->primary_phone).'&ext='.urlencode($userExtension).')' : $client->primary_phone;
          $text = $text . "|" . $client->name . "|" . $phoneExtensionUrl . "|" . "\n";
        }
        else {
          $phoneExtensionUrl = "";
        }
      }
    }
    $text = $text . "---";
    return $this->sendEnhancedResponse($text, true, $responseType);
  }

  function makeJobBookedTable($task, $text, $errorMessage, $client, $data) {
    $responseType = $this->setResponseType($text); // check to see if >all is present
    $text =
"
#### Booked Job : $task->id $errorMessage

| Task Id | User | Client | Type | Title | Problem |
|:--------|:-----|:-------|:-----|:------------|:------------|
";

    if ($task->assigned_to != null) {
      $text = $text . "|" ."[". $task->id ."](' . config('app.url') . '/tasks/support/".$task->id.")" . "|" . User::find($task->assigned_to)->username . "|" .$client->name . "|" . $task->type ."|" . $data['title'] ."|" . $data['problem'] ."|" . "\n";
    }
    else {
      $text = $text . "|" ."[". $task->id ."](' . config('app.url') . '/tasks/support/".$task->id.")" . "|" . 'In the queue' . "|" .$client->name . "|" . $task->type ."|" . $data['title'] ."|" . $data['problem'] ."|" . "\n";
    }
    return $this->sendEnhancedResponse($text, true, $responseType);
  }

  function setupIcingaHosts () {
    $returnedData = new \stdClass();

    $client = new \Buzz\Browser();
    // dd($client);
    $icingaHosts = array(
      array(
        'url' => env('ICINGA_HOST_URL', ''),
        'authKey' => env('ICINGA_AUTH_KEY', '')
      )
    );
    $format = 'json';
    $serviceSettings = array();
    $serviceSettings['target'] = 'service';
    $serviceSettings['columns'] = array('HOST_NAME','SERVICE_NAME','SERVICE_CURRENT_STATE', 'SERVICE_OUTPUT', 'HOST_CURRENT_STATE', 'SERVICE_PROBLEM_HAS_BEEN_ACKNOWLEDGED', 'HOST_LAST_STATE_CHANGE');
    $serviceSettings['filters_json'] = '{"type":"AND","field":[{"type":"atom","field":["HOST_CURRENT_STATE"],"method":["="],"value":[0]},{"type":"OR","field":[{"type":"atom","field":["SERVICE_CURRENT_STATE"],"method":["="],"value":[1]},{"type":"atom","field":["SERVICE_CURRENT_STATE"],"method":["="],"value" : [2] }]}]}';

    $hostSettings['target'] = 'host';
    $hostSettings['columns'] = array('HOST_NAME','HOST_CURRENT_STATE', 'HOST_LAST_STATE_CHANGE', 'HOST_PROBLEM_HAS_BEEN_ACKNOWLEDGED',);
    $hosts = array();
    $services = array();

    foreach ($icingaHosts as $icingaHost)
    {
      $url = $icingaHost['url'];
      $authKey = $icingaHost['authKey'];
      $apiUrl = $url.'/icinga-web/web/api/authkey='.$authKey.'/'.$format;
      $hostResponse = $client->submit($apiUrl, $hostSettings);
      $content = json_decode($hostResponse->getContent());
      $h = $content->result;
      $hosts = array_merge($hosts, $h);

      $returnedData->hosts = $hosts;

      $serviceResponse = $client->submit($apiUrl, $serviceSettings);
      $content = json_decode($serviceResponse->getContent());
      $s = $content->result;
      $services = array_merge($services, $s);

      $returnedData->services = $services;
    }
    return $returnedData;
  }


  function makeIcingaNotAckTable($hosts, $services) {

    $text =  $this->icingaTableHeader();

    $stateIcon = "";
    $acknowledgedIcon = "";
    $sendAcknowledgementIcon = "";



    foreach ($hosts as $host) {
      $stateIcon = $this->setHostStateIcon($host->HOST_CURRENT_STATE);

      if ($host->HOST_PROBLEM_HAS_BEEN_ACKNOWLEDGED === "0") {

        $acknowledgedIcon = ":x:";
        $sendAcknowledgementIcon = "[:speech_balloon:]( https://monitor.wiseserve.net/icingaweb2/dashboard#!/icingaweb2/monitoring/host/acknowledge-problem?host=" . $host->HOST_NAME . ")";


        $host->type = "Host";
        if (($host->HOST_CURRENT_STATE == "1" || $host->HOST_CURRENT_STATE == "2" ) && $host->HOST_PROBLEM_HAS_BEEN_ACKNOWLEDGED === "0") {
          $text = $text . 	"|" ."[". $host->type ."](  https://monitor.wiseserve.net/icingaweb2/dashboard?pane=Muted#!/icingaweb2/monitoring/host/show?host=" . $host->HOST_NAME . ")" . "|" . $host->HOST_NAME . "| - " . "|" . $stateIcon  . "|"  . $acknowledgedIcon . "|" . $sendAcknowledgementIcon  . "| - |" . "\n";
        }
      }
    }

    foreach ($services as $service) {
      $stateIcon = $this->setServiceStateIcon($service->SERVICE_CURRENT_STATE);

      if ($service->SERVICE_PROBLEM_HAS_BEEN_ACKNOWLEDGED === "0") {

          $acknowledgedIcon = ":x:";
          $sendAcknowledgementIcon = "[:speech_balloon:]( https://monitor.wiseserve.net/icingaweb2/dashboard#!/icingaweb2/monitoring/service/acknowledge-problem?host=". $service->HOST_NAME . "&service=" . $service->SERVICE_NAME . ")";
        }

      $service->type = "Service";

      if (($service->SERVICE_CURRENT_STATE == "1" || $service->SERVICE_CURRENT_STATE == "2") && $service->SERVICE_PROBLEM_HAS_BEEN_ACKNOWLEDGED === "0") {
        $text = $text . "|" ."[". $service->type ."](  https://monitor.wiseserve.net/icingaweb2/dashboard#!/icingaweb2/monitoring/service/show?host=". $service->HOST_NAME . "&service=" . $service->SERVICE_NAME . ")" . "|" . $service->HOST_NAME . "|" . $service->SERVICE_NAME . "|" . $stateIcon  . "|" . $acknowledgedIcon . "|". $sendAcknowledgementIcon ."|" . $service->SERVICE_OUTPUT . "|" . "\n";
      }
    }
    return $text;
  }

  function makeIcingaAllTable($hosts, $services) {

    $text = $this->icingaTableHeader();

    $stateIcon = "";
    $acknowledgedIcon = "";
    $sendAcknowledgementIcon = "";

    foreach ($hosts as $host) {
      $stateIcon = $this->setHostStateIcon($host->HOST_CURRENT_STATE);

      if ($host->HOST_PROBLEM_HAS_BEEN_ACKNOWLEDGED === "1") {

        $acknowledgedIcon = ":white_check_mark:";
        $sendAcknowledgementIcon = ":heavy_minus_sign:";

      }
      else {
        $acknowledgedIcon = ":x:";
        $sendAcknowledgementIcon = "[:speech_balloon:]( https://monitor.wiseserve.net/icingaweb2/dashboard#!/icingaweb2/monitoring/host/acknowledge-problem?host=" . $host->HOST_NAME . ")";
      }


      $host->type = "Host";
      if($host->HOST_CURRENT_STATE == "1" || $host->HOST_CURRENT_STATE == "2") {
        $text = $text . 	"|" ."[". $host->type ."](  https://monitor.wiseserve.net/icingaweb2/dashboard?pane=Muted#!/icingaweb2/monitoring/host/show?host=" . $host->HOST_NAME . ")" . "|" . $host->HOST_NAME . "| - " . "|" . $stateIcon  . "|"  . $acknowledgedIcon . "|" . $sendAcknowledgementIcon  . "| - |" . "\n";
      }
    }

    foreach ($services as $service) {

      $stateIcon = $this->setServiceStateIcon($service->SERVICE_CURRENT_STATE);

      if ($service->SERVICE_PROBLEM_HAS_BEEN_ACKNOWLEDGED === "1") {

        $acknowledgedIcon = ":white_check_mark:";
        $sendAcknowledgementIcon = ":heavy_minus_sign:";
      }
      else {
        $acknowledgedIcon = ":x:";
        $sendAcknowledgementIcon = "[:speech_balloon:]( https://monitor.wiseserve.net/icingaweb2/dashboard#!/icingaweb2/monitoring/service/acknowledge-problem?host=". $service->HOST_NAME . "&service=" . $service->SERVICE_NAME . ")";
      }


      $service->type = "Service";

      if($service->SERVICE_CURRENT_STATE == "1" || $service->SERVICE_CURRENT_STATE == "2") {
        $text = $text . "|" ."[". $service->type ."](  https://monitor.wiseserve.net/icingaweb2/dashboard#!/icingaweb2/monitoring/service/show?host=". $service->HOST_NAME . "&service=" . $service->SERVICE_NAME . ")" . "|" . $service->HOST_NAME . "|" . $service->SERVICE_NAME . "|" . $stateIcon  . "|" . $acknowledgedIcon . "|". $sendAcknowledgementIcon ."|" . $service->SERVICE_OUTPUT . "|" . "\n";
      }
    }
    return $text;
  }

  function icingaTableHeader() {
    return "

### Icinga Hosts / Services (may be up to 2 minutes behind)

| Type | Host Name | Service Name | State | Acknowledged | Acknowledge?| Warning / Error |
|:-------|:-------|:-------:|:-------:|:-------:|:-------:|:-------|
";
  }

  function setHostStateIcon($state) {
    if ($state === "1") {
      return ":heavy_exclamation_mark:";
    }
    else {
      return ":question:";
    }
  }

  function setServiceStateIcon($state) {
    if ($state === "2") {
      return ":heavy_exclamation_mark:";
    }
    else if ($state === "1") {
      return ":warning:";
    }
    else {
      return ":question:";
    }
  }

}
?>