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

import { TYPE_SUCCESS } from '@/modules/@common/notify/constants';

import createRequestBody from '../../helpers/createRequestBody';
import { createPlayerAction, setPlayerIsLoadingAction } from '../slices';
import { gqlRequest } from '@/modules/@common/request';
import { showNotificationAction } from '@/modules/layout/redux/slices';
import { typeSelector } from '@/modules/players/Editor/redux/selectors';

const query = `
  mutation CreatePlayer(
    $player: ModulePlayerCreateInputType, 
    $copyFromId: Int
    $shouldCreateTags: Boolean
  ) {
    createPlayer(
      player: $player
      copyFromId: $copyFromId
      shouldCreateTags: $shouldCreateTags
    ) { 
      id
      alias
    }
  }
`;

export default (action$, state$) =>
  action$.pipe(
    ofType(createPlayerAction.type),
    switchMap((action) => {
      const { copyFromId, shouldCreateTags } = action.payload;
      const actions = [];
      const playerType = typeSelector(state$.value);
      const player = createRequestBody(playerType, state$.value);
      const stream$ = gqlRequest({
        query,
        variables: {
          player,
          copyFromId: copyFromId || undefined,
          shouldCreateTags,
        },
      }).pipe(
        switchMap((response) => {
          if (!response.errors.length) {
            Router.push('/player');

            actions.push(
              of(
                showNotificationAction({
                  type: TYPE_SUCCESS,
                  message: 'Player created',
                }),
              ),
            );
          }
          return concat(...actions);
        }),
      );
      return concat(of(setPlayerIsLoadingAction(true)), stream$, of(setPlayerIsLoadingAction(false)));
    }),
  );
