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 { setPlayerIsLoadingAction, updatePlayerAction } from '../slices';
import { gqlRequest } from '@/modules/@common/request';
import { showNotificationAction } from '@/modules/layout/redux/slices';
import { idSelector, typeSelector } from '@/modules/players/Editor/redux/selectors';

const query = `
  mutation UpdatePlayer(
    $id: Int!
    $player: ModulePlayerCreateInputType 
  ) {
    updatePlayer(
      id: $id
      player: $player
    ) { 
      id
    }
  }
`;

export default (action$, state$) =>
  action$.pipe(
    ofType(updatePlayerAction.type),
    switchMap(() => {
      const actions = [];
      const id = idSelector(state$.value);
      const type = typeSelector(state$.value);
      const player = createRequestBody(type, state$.value);
      const stream$ = gqlRequest({
        query,
        variables: {
          id,
          player,
        },
      }).pipe(
        switchMap((response) => {
          if (!response.errors.length) {
            Router.push('/player');
            actions.push(
              of(
                showNotificationAction({
                  type: TYPE_SUCCESS,
                  message: 'Player updated',
                }),
              ),
            );
          }
          return concat(...actions);
        }),
      );

      return concat(of(setPlayerIsLoadingAction(true)), stream$, of(setPlayerIsLoadingAction(false)));
    }),
  );
