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

// Apis from parent
import { api } from 'store/apis';
// Action type
import { StoreAction } from 'store/utils/actions';
import { genericCrudSagas, apolloCall } from 'store/utils/sagas';
import { deepOmit } from 'store/utils/helper';

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

import gql from 'graphql-tag';
import { filterUpdateData } from 'store/utils/adminHelpers';
import content from 'store/content';
import { translatableModel } from 'store/adminModels';
import { ApolloClient, InMemoryCache, createHttpLink } from '@apollo/client';
import actions from './actions';

import selectors from './selectors';

const cache = new InMemoryCache();

const client = new ApolloClient({
  link: createHttpLink({ uri: config.api.eventUrlApollo || config.api.baseUrlApollo || '', fetch }),
  cache,
});

const { Zeus, $ } = zeus;

const formListModel = {
  _id: true,
  title: true,
};
const formModel = {
  ...formListModel,
  formData: {
    title: true,
    label: translatableModel,
    placeholder: translatableModel,
    schema: {
      required: true,
      type: true,
      list: true,
    },
    position: true,
  },
  emailConfirmationData: {
    // eslint-disable-next-line
    MJ_templateId: true,
  },
  marketingData: {
    // eslint-disable-next-line
    AC_listId: true,
  },
};

function* getAllForms(action) {
  const zeusQuery = Zeus.query({
    formsGetMany: [{ pagination: { limit: 100, skip: 0 } }, formListModel],
  });

  const query = gql`
    ${zeusQuery}
  `;

  yield call(apolloCall, {
    query,
    objectReturn: 'formsGetMany',
    actionRes: actions.list.result.action,
  });
}

function* getOneForm(action) {
  const zeusQuery = Zeus.query({
    formsGetOne: [
      { id: action.payload.id },
      {
        ...formModel,
        submissions: [{ pagination: { limit: 100, skip: 0 } }, { _id: true, formData: true }],
      },
    ],
  });

  const query = gql`
    ${zeusQuery}
  `;

  yield call(apolloCall, {
    query,
    objectReturn: 'formsGetOne',
    actionRes: actions.detail.result.action,
  });
}

function* getDetailOneForm(action) {
  const zeusQuery = Zeus.query({ formsGetOne: [{ id: action.payload.id }, formModel] });

  const query = gql`
    ${zeusQuery}
  `;

  yield call(apolloCall, {
    query,
    objectReturn: 'formsGetOne',
    actionRes: actions.detailFormData.result.action,
  });
}

function* addNewForm(action) {
  const zeusMutation = Zeus.mutation({
    formsAddOne: [
      {
        input: $`data`,
      },
      formModel,
    ],
  });

  const mutate = gql`
    ${zeusMutation}
  `;

  yield call(apolloCall, {
    mutate,
    objectReturn: 'formsAddOne',
    data: action.payload,
    actionRes: actions.add.result.action,
    callback: action.payload.callback,
  });
}

function* updateOneForm(action) {
  const zeusMutation = Zeus.mutation({
    formsEditOne: [
      {
        input: $`data`,
        id: $`id`,
      },
      formModel,
    ],
  });

  const mutate = gql`
    ${zeusMutation}
  `;

  const filteredData = filterUpdateData(action.payload.model, action.payload.data);

  action.payload.data = filteredData;

  yield call(apolloCall, {
    mutate,
    objectReturn: 'formsEditOne',
    data: deepOmit(action.payload, ['__typename', '_id']),
    actionRes: actions.update.result.action,
    callback: action.payload.callback,
  });
}

function* deleteForm(action) {
  const zeusMutation = Zeus.mutation({
    formsDeleteOne: [
      {
        id: $`id`,
      },
      {
        _id: true,
        title: true,
      },
    ],
  });

  const mutate = gql`
    ${zeusMutation}
  `;

  yield call(apolloCall, {
    mutate,
    objectReturn: 'formsDeleteOne',
    data: action.payload,
    actionRes: actions.delete.result.action,
    callback: action.payload.callback,
  });
}

function* exportFormData(action) {
  console.log('action', action);
  const { payload } = action;

  const zeusQuery = Zeus.query({
    exportFormSubmissions: [
      { formId: $`formId` },
      {
        url: true,
      },
    ],
  });

  const query = gql`
    ${zeusQuery}
  `;

  yield call(apolloCall, {
    query,
    objectReturn: 'exportFormSubmissions',
    actionRes: actions.exportFormData.result.action,
    callback: payload.callback,
    data: { formId: payload.formId },
    client,
  });
}

function* formsWatchers() {
  yield all([
    yield takeEvery(actions.list.request.constant, getAllForms),
    yield takeEvery(actions.detail.request.constant, getOneForm),
    yield takeEvery(actions.add.request.constant, addNewForm),
    yield takeEvery(actions.detailFormData.request.constant, getDetailOneForm),
    yield takeEvery(actions.delete.request.constant, deleteForm),
    yield takeEvery(actions.update.request.constant, updateOneForm),
    yield takeEvery(actions.exportFormData.request.constant, exportFormData),
  ]);
}

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