<?php

namespace App\Classes\MikrotikService;

use RouterOS\Exceptions\ClientException;
use RouterOS\Exceptions\ConfigException;
use RouterOS\Exceptions\QueryException;
use RouterOS\Config;
use RouterOS\Client;


class MikrotikConfig
{
    protected Client $client;

    public function __construct(string $host, string $user, string $pass, int $port = 8728)
    {
        try {
            $config = new Config([
                "host" => $host,
                "user" => $user,
                "pass" => $pass,
                "port" => $port,
                "socket_timeout" => 10,
            ]);

            $this->client = new Client($config);
        } catch (ClientException $exception) {
            $this->ignoreMkOrThrowError("Mikrotik Not Connecting");
        } catch (ConfigException $exception) {
            $this->ignoreMkOrThrowError("Mikrotik Information Not Correct");
        } catch (QueryException $exception) {
            $this->ignoreMkOrThrowError("Unable to process Mikrotik query.");
        }
    }

    private function ignoreMkOrThrowError(string $message = "", int $code = 0)
    {
        if (globalPermission("ignore-mikrotik-check")) {
            return;
        }
        throw new \Exception($message, $code);
    }

    protected function checkIfUserInIgnoreList($username)
    {
        $list = ignoreMKClientList();
        return in_array($username, $list) || globalPermission("ignore-mikrotik-check");
    }

    protected function runQuery($queryObject)
    {
        return $this->client->query($queryObject)->read();
    }

    protected function queryMapper($queryObject, $queryEntries)
    {
        foreach ($queryEntries as $queryKey => $queryValue) {
            $queryObject->equal($queryKey,  $queryValue);
        }
        return $queryObject;
    }
}
