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

// Apis from parent
import { api } from 'store/apis';
// Action type
import { StoreAction } from 'store/utils/actions';
import { apiCall, apolloCall } from 'store/utils/sagas';
import { zeus, config, stats } from 'config/general';
import gql from 'graphql-tag';
import _ from 'lodash';

import { gqlConvert } from 'store/utils/adminHelpers';
import actions from './actions';

function* getStats(action: StoreAction): void {
  const payload = action.payload;
  yield call(apiCall, {
    api: api.stats[payload.api],
    actionRes: (data): void => actions.get.result.action({ name: payload.name, data }),
    noLoading: payload.noLoading,
  });
}

function* getStatsApollo(action: StoreAction): void {
  const { Zeus } = zeus;

  const payload = action.payload || {};

  const { fields, name, resource, inputs, noLoading } = payload;

  const apiInput = {
    ...inputs,
  };

  const statsModel = _.get(payload, payload.statsModel || 'stats');

  const outputModel = fields || gqlConvert(statsModel);

  if (!outputModel) {
    return;
  }
  let zeusQuery;
  try {
    zeusQuery = Zeus.query({
      [resource]: [apiInput, outputModel],
    });
  } catch (error) {
    console.log('error detail', error);
    return;
  }

  console.log('query', zeusQuery);

  const query = gql`
    ${zeusQuery}
  `;

  yield call(apolloCall, {
    objectReturn: name,
    query,
    actionRes: data => actions.getApollo.result.action({ name, data }),
    noLoading,
  });
}

function* getAllStats(action: StoreAction): void {
  const payload = action.payload;

  if (!stats) return;
  for (let index = 0; index < stats.length; index++) {
    const element = stats[index];

    console.log('element', element);

    if (element.apollo) {
      yield put(
        actions.getApollo.request.action({
          ...element,
          name: element.name || element.resource,
          noLoading: !(payload && payload.noLoading === false),
        }),
      );
    } else {
      yield put(
        actions.get.request.action({
          api: element.api,
          name: element.name || element.api,
          noLoading: !(payload && payload.noLoading === false),
        }),
      );
    }
  }
}

function* refreshAllStats(): void {
  yield call(getAllStats, actions.getAll.request.action());
}

function* statsWatchers(): void {
  yield all([
    yield takeEvery(actions.getAll.request.constant, getAllStats),
    yield takeEvery(actions.get.request.constant, getStats),
    yield takeEvery(actions.getApollo.request.constant, getStatsApollo),
    yield takeEvery(actions.refreshAll.request.constant, refreshAllStats),
  ]);
}

export default function* saga(): void {
  yield call(statsWatchers);
}
