<?php

use PEAR2\Net\RouterOS;
require __DIR__."/mfRouteros_Item.php";

class mfRouteros extends mfBaseModel {
  
  private $hostname;
  private $username;
  private $password;
  private $ros = false;
  
  protected function init() {
    if(defined("MFROS_HOSTNAME")) {
      $this->hostname(MFROS_HOSTNAME);
    }
    if(defined("MFROS_USERNAME")) {
      $this->username(MFROS_USERNAME);
    }
    if(defined("MFROS_PASSWORD")) {
      $this->password(MFROS_PASSWORD);
    }
  }
  
  private function _connect() {
    $this->ros = new RouterOS\Client($this->hostname,$this->username,$this->password,8729,false,3);
  }
  
  public function get($table, $filter = array()) {
    if(!$this->ros) $this->_connect();
    
    if(substr($table, 0, 1) != '/') {
      $table = "/".$table;
    }
    
    $req = new RouterOS\Request("$table print");
    
    $q = false;
    if(count($filter)) {
      foreach($filter as $name => $value) {
        if($q === false) {
          $q = RouterOS\Query::where($name,$value);
        } else {
          $q->andWhere(RouterOS\Query::where($name,$value));
        }
      }
      $req->setQuery($q);
    }
    
    $responses = $this->ros->sendSync($req);
    
    $answers = [];
    foreach($responses as $response) {
      $answer = new mfRouteros_Item($response);
      if($answer->propcount()) {
        $answers[] = $answer;
      }
    }

    return $answers;
    
  }
  
  public function getFirst($table, $filter = array()) {
    $answers = $this->get($table,$filter);
    return array_shift($answers);
  }
  
  public function getLast($table, $filter = array()) {
    $answers = $this->get($table,$filter);
    return array_pop($answers);
  }
  
  
  public function set($table, $action, $set=array(), $filter = array()) {
    if(!$this->ros) $this->_connect();
    
    if(substr($table, 0, 1) != '/') {
      $table = "/".$table;
    }
    
    $item = $this->getFirst($table, $filter);
    $id = $item['.id'];
    
    $req = new RouterOS\Request("$table $action");
    
    $req->setArgument("numbers", $id);
    if(count($set)) {
      foreach($set as $name => $value) {
        $req->setArgument($name, $value);
      }
    }
    
    $resp = $this->ros->sendSync($req);
    
    if($resp->getType() !== RouterOS\Response::TYPE_FINAL) {
      return false;
    }
    return true;
  }
  
  /* accessors */
  public function hostname($hostname=false) {
    if($hostname) {
      $this->hostname = $hostname;
    }
    return $this->hostname;
  }

  public function username($username=false) {
    if($username) {
      $this->username = $username;
    }
    return $this->username;
  }
  
  public function password($password=false) {
    if($password) {
      $this->password = $password;
    }
    return $this->password;
  }
  
}