<?php

namespace Longman\TelegramBot\Commands\UserCommands;

use GuzzleHttp\Client;
use GuzzleHttp\Exception\RequestException;
use Longman\TelegramBot\Commands\UserCommand;
use Longman\TelegramBot\Request;
use Longman\TelegramBot\Entities\ReplyKeyboardMarkup;


/**
 * User "/temp" command
 */
class StatusCommand extends UserCommand
{
    /**#@+
     * {@inheritdoc}
     */
    protected $name = 'status';
    protected $description = 'show Raspberry Pi sensor status.';
    protected $usage = '/status <pi-machine>\n\neg: /status office\n/status home';
    protected $version = '1.0.0';
    /**#@-*/
    /**
     * {@inheritdoc}
     */
    public function execute()
    {
        $message = $this->getMessage();
        $chat_id = $message->getChat()->getId();
        $message_id = $message->getMessageId();
        $text = $message->getText(true);
        $sender = '@' . $message->getFrom()->getUsername();
        if ( !strcmp($text,'office')) {

	$data = json_decode($this->getPiData("officepi"),true);

		if (strlen($data['pi'])>3) {
			$machine = $data['pi'];
			$status = $data['status'];
			$time = $data['time'];
		        $text = "[$machine]\n$time\nB0-24, Al-Farabi, UiTM Perlis\n\nStatus: $status";
		} else { 
			$text = $sender . " unable to get temperature data for $text";

		}
        } else if   ( !strcmp($text,'home')) {

		 $rowpi = json_decode($this->getPiData("oldpi"),true);

		 foreach ($rowpi as $data) {

                	 if (strlen($data['pi'])>3) {
				  $machine = $data['pi'];
	                          $status = $data['status'];
        	                  $time = $data['time'];

	
                        	   $text = "[$machine]\n$time\nJln Langgar, Alor Setar\n\nStatus: $status";
	                } else { 
        	                   $text = $sender . " unable to get temperature data for $text";

                	}
		}

	} else {
		 $text = "sorry please specify if you want to get \"office\" or \"home\" sensor's current status.\n\neg:\n/status home\n/status office\n\n";
        }
        $data = [
            'chat_id' => $chat_id,
            'text'    => $text,
        ];
        return Request::sendMessage($data);
    }

   public function getPiData($data)
   {

//	return "{\"pi\":\"officepi\",\"temp\":\"30.9 C\",\"humidity\":\"64 %\",\"time\":\"2016-08-15T03:12:05+08:00\",\"fuzzy\":\"39 seconds ago\"}";
	$client = new Client(['base_uri' => 'https://logger.mypapit.net/pi/bot/']);
	$path = 'getstatus.php';
	$query = [
	  'pi' => $data,
	];

	try {
            $response = $client->get($path, ['query' => $query]);
        } catch (RequestException $e) {
//            throw new TelegramException($e->getMessage());
		return "{\"pi\":\"officepi\",\"temp\":\"$e->getMessage()\",\"humidity\":\"64 %\",\"time\":\"2016-08-15T03:12:05+08:00\",\"fuzzy\":\"39 seconds ago\"}";
        }

	return (string)$response->getBody();

   }

}
?>
