<?php

namespace App\Classes\MikrotikService\MikrotikStaticIPLogic;

use RouterOS\Query;

trait ArpProtocol
{
    public function getArpList($arpAddress = null)
    {
        $arpQuery = new Query("/ip/arp/print");

        if ($arpAddress) {
            $arpQuery->where("address", $arpAddress);
        }

        $arpList =  $this->runQuery($arpQuery);

        if (sizeof($arpList) === 0) {
            return null;
        }

        return $arpAddress ? $arpList[0] : $arpList;
    }

    public function createArp($aprInfo)
    {
        $arpQuery = new Query("/ip/arp/add");

        $this->queryMapper($arpQuery, $aprInfo);

        $response = $this->runQuery($arpQuery);

        if (!array_key_exists("ret", $response['after'])) {
            throw new \Exception($response["after"]["message"], 404);
        }

        return $response;
    }

    public function updateArp($arpAddress, $updatedInfo)
    {
        $existingArp = $this->getArpList($arpAddress);

        $arpUpdateQuery = new Query("/ip/arp/set");

        $arpUpdateQuery->equal(".id", $existingArp['.id']);

        $this->queryMapper($arpUpdateQuery,  $updatedInfo);

        $response = $this->runQuery($arpUpdateQuery);
        if (sizeof($response) !== 0) {
            throw new \Exception($response["after"]["message"], 404);
        }

        return $response;
    }

    public function deleteArp($arpAddress)
    {

        $arpQuery = new Query("/ip/arp/remove");

        $arp = $this->getArpList($arpAddress);

        $arpQuery->equal("numbers", $arp['.id']);

        $response = $this->runQuery($arpQuery);

        if (sizeof($response) !== 0) {
            throw new \Exception("Something went wrong while deleting arp.");
        }

        return $response;
    }
}
