<?php

namespace App\Classes\MikrotikService\MikrotikStaticIPLogic;

use RouterOS\Query;

trait FirewallFilter
{
    public function createFirewallFilter($filterInfo)
    {
        $createFirewallFilterQuery = new Query("/ip/firewall/filter/add");

        $this->queryMapper($createFirewallFilterQuery, $filterInfo);

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

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


        return $response;
    }

    public function getStaticFirewallFilterInfo($filedName = null, $filedValue = null)
    {
        $firewallQuery = new Query("/ip/firewall/filter/print");

        if ($filedName && $filedValue) {
            $firewallQuery->where($filedName, $filedValue);
        }

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

        if ($filedName && sizeof($response) == 0) {
            return null;
        }

        return ($filedName && $filedValue) ? $response[0] : $response;
    }

    public function updateFirewallFilter($firewallIpAddress, $updatedInfo)
    {
        $existingFirewallFilter = $this->getStaticFirewallFilterInfo("src-address", $firewallIpAddress);

        $firewallUpdateQuery = new Query("/ip/firewall/filter/set");

        $firewallUpdateQuery->equal(".id", $existingFirewallFilter['.id']);

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

        $response = $this->runQuery($firewallUpdateQuery);
        if (sizeof($response) !== 0) {
            throw new \Exception("Something went wrong while updating firewall.");
        }

        return $response;
    }

    public function deleteFirewallFilter($firewallIpAddress)
    {
        $existingFirewallFilter = $this->getStaticFirewallFilterInfo("src-address", $firewallIpAddress);

        $firewallDeleteQuery = new Query("/ip/firewall/filter/remove");

        $firewallDeleteQuery->equal("numbers", $existingFirewallFilter['.id']);

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

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

        return $response;
    }
}
