import { ofType } from 'redux-observable';
import { concat, of } from 'rxjs';
import { switchMap } from 'rxjs/operators';

import { getDefaultTempForm, modelsByProviders } from '../../helpers';
import { getAllAnalyticsModelsComputedSelector, getProvidersListComputedSelector } from '../selectors';
import { onAddFormAction, saveConfigurationDataOnServerAction, updateConfigurationByPropAction } from '../slices';

export default (action$, state$) =>
  action$.pipe(
    ofType(onAddFormAction.type),
    switchMap(({ payload: { providerName } }) => {
      const providerModelName = modelsByProviders[providerName];
      const model = getAllAnalyticsModelsComputedSelector(state$.value)[providerModelName];
      const { providers } = getProvidersListComputedSelector(state$.value);
      const { tempForm } = model;

      const updatedFormList = {
        ...model,
        formList: model.formList.concat({
          formId: `${Math.random()}-${Math.random()}`,
          model: tempForm.model.selected,
          category: tempForm.category.selected,
          lowerBound: tempForm.lowerBound.value,
          maxResults: tempForm.maxResults.value,
        }),
        tempForm: getDefaultTempForm(providers, providerName),
      };

      return concat(
        of(
          updateConfigurationByPropAction({
            [providerModelName]: updatedFormList,
          }),
        ),
        of(saveConfigurationDataOnServerAction([providerModelName])),
      );
    }),
  );
