const FEST_AGENT_STATUS_URL = 'http://localhost:38473/status';
const FEST_AGENT_POLL_MS = 120000;
const FEST_AGENT_TIMEOUT_MS = 3000;

function renderFestAgentStatus(el, status) {
  if (!el) {
    return;
  }

  const online = !!(status && status.online);
  const endpointId = status && status.endpointId != null ? status.endpointId : null;

  if (online && endpointId != null) {
    el.innerHTML =
      '<span class="badge bg-label-success ms-2 text-nowrap">' +
      '<i class="bx bx-check-circle me-1"></i>FestAgent · #' + endpointId +
      '</span>';
    return;
  }

  if (online) {
    el.innerHTML =
      '<span class="badge bg-label-success ms-2 text-nowrap">' +
      '<i class="bx bx-check-circle me-1"></i>FestAgent attivo</span>';
    return;
  }

  el.innerHTML =
    '<span class="badge bg-label-danger ms-2 text-nowrap">' +
    '<i class="bx bx-x-circle me-1"></i>FestAgent non raggiungibile</span>';
}

function fetchFestAgentStatus() {
  const controller = new AbortController();
  const timeoutId = setTimeout(function () {
    controller.abort();
  }, FEST_AGENT_TIMEOUT_MS);

  return fetch(FEST_AGENT_STATUS_URL, {
    method: 'GET',
    headers: {
      Accept: 'application/json',
    },
    signal: controller.signal,
  })
    .then(function (response) {
      return response.json();
    })
    .then(function (data) {
      return {
        online: !!(data && data.ok),
        endpointId: data && data.endpoint ? data.endpoint.endpoint_id : null,
      };
    })
    .finally(function () {
      clearTimeout(timeoutId);
    });
}

function updateLocalFestAgentStatusFooter() {
  const el = document.getElementById('status_local_festagent');
  if (!el) {
    return Promise.resolve(false);
  }

  return fetchFestAgentStatus()
    .then(function (status) {
      renderFestAgentStatus(el, status);
      return status.online;
    })
    .catch(function () {
      renderFestAgentStatus(el, { online: false, endpointId: null });
      return false;
    });
}

function startFestAgentStatusWatcher() {
  if (!document.getElementById('status_local_festagent')) {
    return;
  }

  updateLocalFestAgentStatusFooter();

  if (window.__festAgentStatusInterval) {
    clearInterval(window.__festAgentStatusInterval);
  }

  window.__festAgentStatusInterval = setInterval(updateLocalFestAgentStatusFooter, FEST_AGENT_POLL_MS);
}

function getLocalFestAgentStatus(showNotification) {
  return updateLocalFestAgentStatusFooter().then(function (online) {
    if (!showNotification || typeof Notyf === 'undefined') {
      return online;
    }

    const notyf = new Notyf({
      duration: 3000,
      position: { x: 'right', y: 'top' },
    });

    if (online) {
      notyf.success('FestAgent è in esecuzione');
    } else {
      notyf.error('FestAgent non è in esecuzione su questo PC');
    }

    return online;
  });
}

document.addEventListener('DOMContentLoaded', startFestAgentStatusWatcher);

window.getLocalFestAgentStatus = getLocalFestAgentStatus;
window.updateLocalFestAgentStatusFooter = updateLocalFestAgentStatusFooter;
window.fetchFestAgentStatus = fetchFestAgentStatus;
window.renderFestAgentStatus = renderFestAgentStatus;
