<?php

namespace app\models\mikrotik\system;

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 Keys extends Model {

    public $id;
    public $user;
    public $bits;
    public $key_owner;
    public $public_key_file;

    public function rules() {
        return [
            ['id', 'string'],
            ['user', 'string'],
            ['bits', 'string'],
            ['key_owner', 'string'],
            ['public_key_file', 'string'],
        ];
    }

    public function getAll() {
        $connect = MikrotikConnect::Instance();
        $getRequest = new RouterOS\Request('/user/ssh-keys/getall');
        $responses = $connect->getConnection()->sendSync($getRequest);
        $return = array();
        foreach ($responses as $response) {
            if ($response->getProperty('.id') != null) {
                $c = new Keys();
                $c->id = $response->getProperty('.id');
                $c->user = $response->getProperty('user');
                $c->bits = $response->getProperty('bits');
                $c->key_owner = $response->getProperty('key-owner');
                $c->public_key_file = $response->getProperty('public-key-file');
                $return[] = $c;
            }
        }
        return $return;
    }

    public function create() {
        $connect = MikrotikConnect::Instance();
        $setRequest = new RouterOS\Request('/user/ssh-keys/import');
        if ($this->user != "") {
            $setRequest->setargument('user', $this->user);
        }
        if ($this->public_key_file != "") {
            $setRequest->setargument('public-key-file', $this->public_key_file);
        }
        $resp = $connect->getConnection()->sendSync($setRequest);
        if ($resp->getType() !== RouterOS\Response::TYPE_FINAL) {
            return $resp->getProperty('message');
        } else {
            return '1';
        }
    }

    public function delete($id) {
        $connect = MikrotikConnect::Instance();
        $util = new RouterOS\Util($connect->getConnection());
        $util->setMenu('/user/ssh-keys');
        $util->remove(RouterOS\Query::where('.id', $id));
        return;
    }

    public function getFiles() {
        $connect = MikrotikConnect::Instance();
        $getRequest = new RouterOS\Request('/file/getall');
        $responses = $connect->getConnection()->sendSync($getRequest);
        $return = array();
        foreach ($responses as $response) {
            if ($response->getProperty('.id') != null) {
                $return[$response->getProperty('name')] = $response->getProperty('name');
            }
        }
        return $return;
    }

}
