<?php

namespace app\models\mikrotik\tools;

use yii\base\Model;
use Yii;

require_once 'PEAR2_Net_RouterOS-1.0.0b5.phar';

use PEAR2\Net\RouterOS;
use app\models\mikrotik\MikrotikConnect;

class Ping extends Model {

    public $dst;
    public $interface = 'none';
    public $count = '4';
    public $timeout = '1s';
    public $response;

    public function rules() {
        return [
            ['dst', 'ip'],
            ['interface', 'string'],
            ['count', 'integer'],
            ['timeout', 'string'],
            ['response', 'string'],
        ];
    }

    public function ping() {
        $connect = MikrotikConnect::Instance();
        $setRequest = new RouterOS\Request('/ping');
        $setRequest->setargument('address', $this->dst);
        $setRequest->setargument('count', $this->count);
        $setRequest->setargument('interval', $this->timeout);
        if ($this->interface != 'none') {
            $setRequest->setargument('interface', $this->interface);
        }
        $ret = array();
        $x = '0';
        $responses = $connect->getConnection()->sendSync($setRequest);
        foreach ($responses as $response) {

            if ($response->getProperty('host') != null) {
                $ret[$x]['seq'] = $response->getProperty('seq');
                $ret[$x]['host'] = $response->getProperty('host');
                $ret[$x]['time'] = $response->getProperty('time');
                $ret[$x]['size'] = $response->getProperty('size');
                $ret[$x]['ttl'] = $response->getProperty('ttl');
                $ret[$x]['loss'] = $response->getProperty('packet-loss');
                $x++;
            }
        }

//        $pingRequest = new RouterOS\Request('/tool traceroute count=1 timeout=1 size=56 protocol=icmp');
//        $results = $connect->getConnection()->sendSync($pingRequest->setArgument('address', $this->dst));

        return $ret;
    }

    public function names() {

        $connect = MikrotikConnect::Instance();
        $printRequest = new RouterOS\Request('/interface/getall');
        $responses = $connect->getConnection()->sendSync($printRequest);
        foreach ($responses as $response) {

            if ($response->getProperty('.id') != null) {
                $ret[$response->getProperty('name')] = $response->getProperty('name');
            }
        }
        return $ret;
    }

}
