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

import { modelsByProviders } from '../../helpers';
import { getAllAnalyticsModelsComputedSelector } from '../selectors';
import { onChangeModelTempFormAction, updateConfigurationByPropAction } from '../slices';

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

      const copyTempForm = { ...model.tempForm };

      copyTempForm[fieldName] = { ...copyTempForm[fieldName], ...value };

      const updatedFormList = {
        ...model,
        tempForm: copyTempForm,
      };

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