import { put, takeEvery, all, call } from 'redux-saga/effects';

import gql from 'graphql-tag';

// Action type
import { StoreAction } from 'store/utils/actions';

import { apolloCall } from 'store/utils/apollo';

import { config, zeus } from 'config/general';

import actions from './actions';
import selectors from './selectors';
import * as models from './models';

const { Zeus, $ } = zeus;

const list = type =>
  function*(action: StoreAction) {
    const payload = action.payload || {};

    const search = { ressourceType: type };

    const zeusQuery = Zeus.query({
      listsGetMany: [search, models.listModel],
    });

    const query = gql`
      ${zeusQuery}
    `;

    console.log('zeus query');

    yield call(apolloCall, {
      objectReturn: 'listsGetMany',
      query,
      name: 'listsGetMany',
      actionRes: actions[type].result.action,
      noLoading: payload.noLoading,
      callback: payload.callback,
      callbackError: payload.callbackError,
    });
  };

const categories = type =>
  function*(action) {
    const payload = action.payload || {};

    const search = { ressourceType: 'none' };

    const zeusQuery = Zeus.query({
      categoriesGetMany: [search, models.categoryModel],
    });

    const query = gql`
      ${zeusQuery}
    `;

    yield call(apolloCall, {
      objectReturn: 'categoriesGetMany',
      query,
      name: 'categoriesGetMany',
      actionRes: actions.categories.result.action,
      noLoading: payload.noLoading,
      callback: payload.callback,
      callbackError: payload.callbackError,
    });
  };

function* generalWatchers() {
  yield all([
    takeEvery(actions.equipment.request.constant, list('equipment')),
    takeEvery(actions.feature.request.constant, list('feature')),
    // takeEvery(actions.categories.request.constant, categories),
  ]);
}

export default function* saga() {
  yield call(generalWatchers);
}
