import { createSlice } from '@reduxjs/toolkit';

import { HB_CONNECTOR_STATUSES, HB_FORMATS } from '../../constants';

const initialConnectorFormState = {
  name: '',
  code: '',
  params: [],
  parameters: '{}',
  comments: '',
  status: HB_CONNECTOR_STATUSES.enabled,
  format: HB_FORMATS[0].value,
};

const initialState = {
  connectors: [],
  totalCount: 0,
  page: 0,
  rowsPerPage: 10,
  search: '',

  filterStatus: HB_CONNECTOR_STATUSES.enabled,
  filterFormat: HB_FORMATS[0].value,

  ...initialConnectorFormState,
};

export const slice = createSlice({
  name: '@@hbConnectors/HB_CONNECTORS',
  initialState,

  reducers: {
    setFieldAction: (state, action) => {
      Object.entries(action.payload).forEach(([key, value]) => {
        state[key] = value;
      });
    },
    resetFormAction: (state) => {
      Object.keys(initialConnectorFormState).forEach((key) => {
        state[key] = initialConnectorFormState[key];
      });
    },

    getConnectorsAction: (state) => state,
    getConnectorByIdAction: (state) => state,
    createConnectorAction: (state) => state,
    updateConnectorAction: (state) => state,
  },
});

export const {
  setFieldAction,
  resetFormAction,
  getConnectorsAction,
  getConnectorByIdAction,
  createConnectorAction,
  updateConnectorAction,
} = slice.actions;

export default slice.reducer;
