<?php

namespace idoit\Module\SyneticsJdisc\Model;

use isys_module_synetics_jdisc;

abstract class AbstractJDiscDao
{
    protected ?int $serverId = null;

    /**
     * Try to set the serverId, use the default server if id is not provided
     *
     * @param int|null $serverId
     * @return bool
     */
    public function init(?int $serverId): bool
    {
        $jdisc   = new isys_module_synetics_jdisc();
        // get all servers (raw data)
        $servers = $jdisc->get_jdisc_servers_as_array(true);

        if (empty($servers)) {
            return false;
        }

        if ($serverId === null) {
            foreach ($servers as $id => $server) {
                if ($server['isys_jdisc_db__default_server'] === '1') {
                    $this->serverId = $id;
                    return true;
                }
            }
            return false;
        }

        if (!array_key_exists($serverId, $servers)) {
            return false;
        }

        $this->serverId = $serverId;
        return true;
    }

    public function getServerId(): ?int
    {
        return $this->serverId;
    }
}
