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

import {
  FORM_SUBMIT_MODE_CREATE,
  FORM_SUBMIT_MODE_DUPLICATE,
  FORM_SUBMIT_MODE_UPDATE,
} from '@/modules/forms/constants';

import * as selectors from '../selectors';
import {
  createTemplateAction,
  duplicateTemplateAction,
  saveProcessAction,
  setFieldAction,
  updateTemplateAction,
} from '../slices';
import { gqlRequest } from '@/modules/@common/request';

const query = `
  mutation UploadFormTemplateImage(
    $picture: String,
    $fileName: String,
  ) {
    uploadFormTemplateImage(
      picture: $picture
      fileName: $fileName 
    ) {
       url
    }
  }
`;

export default (action$, state$) =>
  action$.pipe(
    ofType(saveProcessAction.type),
    switchMap((action) => {
      const { thumbFile, formSubmitMode } = action.payload;

      const image = selectors.imageSelector(state$.value);

      const stream$ = gqlRequest({
        query,
        variables: {
          picture: thumbFile,
          fileName: 'thumb.png',
        },
      }).pipe(
        switchMap((response) => {
          if (!response.errors.length) {
            const { url: thumb } = response.data.uploadFormTemplateImage;
            const [logo, banner] = image;
            const actionMap = [
              {
                action: createTemplateAction,
                isActive: formSubmitMode === FORM_SUBMIT_MODE_CREATE,
              },
              {
                action: updateTemplateAction,
                isActive: formSubmitMode === FORM_SUBMIT_MODE_UPDATE,
              },
              {
                action: duplicateTemplateAction,
                isActive: formSubmitMode === FORM_SUBMIT_MODE_DUPLICATE,
              },
            ];

            const run = actionMap.find((a) => a.isActive);

            return concat(
              of(
                setFieldAction({
                  image: [logo, banner, thumb],
                }),
              ),
              of(run.action()),
            );
          }

          return EMPTY;
        }),
      );

      return concat(stream$);
    }),
  );
