<?php

namespace app\models\mikrotik\ip\firewall;

require_once 'PEAR2_Net_RouterOS-1.0.0b5.phar';

use yii\base\Model;
use Yii;
use PEAR2\Net\RouterOS;
use app\models\mikrotik\MikrotikConnect;

class Serviceports extends Model {

    public $id;
    public $name;
    public $ports;
    public $disabled;

    public function rules() {
        return [
            ['id', 'string'],
            ['name', 'string'],
            ['ports', 'string'],
            ['disabled', 'string'],
        ];
    }

    public function getAll() {
        $connect = MikrotikConnect::Instance();
        $getRequest = new RouterOS\Request('/ip/firewall/service-port/getall');
        $responses = $connect->getConnection()->sendSync($getRequest);
        $return = array();
        foreach ($responses as $response) {
            if ($response->getProperty('.id') != null) {
                $c = new Serviceports();
                $c->id = $response->getProperty('.id');
                $c->name = $response->getProperty('name');
                $c->ports = $response->getProperty('ports');
                $c->disabled = $response->getProperty('disabled');
                $return[] = $c;
            }
        }
        return $return;
    }

    public function update($id) {
        $connect = MikrotikConnect::Instance();
        $setRequest = new RouterOS\Request('/ip/firewall/service-port/set');
        $setRequest->setargument('.id', $id);
        if ($this->ports != "") {
            $setRequest->setargument('ports', $this->ports);
        }
        $connect->getConnection()->sendSync($setRequest);
    }

    public function get($id) {
        $connect = MikrotikConnect::Instance();
        $getRequest = new RouterOS\Request('/ip/firewall/service-port/print');
        $getRequest->setQuery(RouterOS\Query::where('.id', $id));
        $responses = $connect->getConnection()->sendSync($getRequest);
        foreach ($responses as $response) {
            if ($response->getProperty('.id') != null) {
                $this->id = $id;
                $this->name = $response->getProperty('name');
                $this->ports = $response->getProperty('ports');
                $this->disabled = $response->getProperty('disabled');
            }
        }
        return;
    }

    public function disable($id) {
        $connect = MikrotikConnect::Instance();
        $setRequest = new RouterOS\Request('/ip/firewall/service-port/disable');
        $setRequest->setArgument('.id', $id);
        $connect->getConnection()->sendSync($setRequest);
        return;
    }

    public function enable($id) {
        $connect = MikrotikConnect::Instance();
        $setRequest = new RouterOS\Request('/ip/firewall/service-port/enable');
        $setRequest->setArgument('.id', $id);
        $connect->getConnection()->sendSync($setRequest);
        return;
    }

}
