import {useContext, useDebugValue} from 'react';

import {DashboardsContext} from 'src/context';
import {lookupService} from 'src/lib';

export const useServices = () => {
  const context = useContext(DashboardsContext);

  let result = [];
  if (context.currentDashboardId) {
    const currentDashboard = context.dashboards.find((dashboard) => {
      return dashboard.id === context.currentDashboardId;
    });
    result = currentDashboard.services;
  }
  useDebugValue(result);

  return result;
};

export const useService = (kind, instance) => {
  const context = useContext(DashboardsContext);

  const result = lookupService(context.dashboards, kind, instance);
  useDebugValue(result);

  return result;
};

export const useSaveServiceCharacteristics = () => {
  const context = useContext(DashboardsContext);

  const result = context.saveServiceCharacteristics;
  useDebugValue(result);

  return result;
};

export const useSaveServiceLayout = () => {
  const context = useContext(DashboardsContext);

  const result = context.saveServiceLayout;
  useDebugValue(result);

  return result;
};

export const useNukeService = () => {
  const context = useContext(DashboardsContext);

  const result = context.nukeService;
  useDebugValue(result);

  return result;
};

export const useAddService = () => {
  const context = useContext(DashboardsContext);

  const result = context.addService;
  useDebugValue(result);

  return result;
};

export const useServicesSavingState = () => {
  const context = useContext(DashboardsContext);

  const result = {
    lastSaveTimestamp: context.lastSaveTimestamp,
    lastSaveError: context.lastSaveError,
    isSaving: context.isSaving,
  };
  useDebugValue(result);

  return result;
};

export const useWebSocketState = () => {
  const context = useContext(DashboardsContext);

  const result = {
    isWebSocketConnected: context.isWebSocketConnected,
  };
  useDebugValue(result);

  return result;
};

export const useDashboards = () => {
  const context = useContext(DashboardsContext);

  const result = context.dashboards || [];
  useDebugValue(result);

  return result;
};

export const useCurrentDashboardId = () => {
  const context = useContext(DashboardsContext);

  const result = context.currentDashboardId;
  useDebugValue(result);

  return result;
};

export const useSetCurrentDashboardId = () => {
  const context = useContext(DashboardsContext);

  const result = context.setCurrentDashboardId;
  useDebugValue(result);

  return result;
};

export const useDashboardsHash = () => {
  const context = useContext(DashboardsContext);

  const result = context.dashboardsHash;
  useDebugValue(result);

  return result;
};

export const useAddDashboard = () => {
  const context = useContext(DashboardsContext);

  const result = context.addDashboard;
  useDebugValue(result);

  return result;
};
