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

import { QUERY_PARAM_PLAYLIST } from '@/modules/editorial/constants/routing';
import { PLAYLIST_TYPE } from '@/modules/editorial/RightSideBar/TabPlaylist/Edit/constants';

import { getPlaylistByIdAction } from '../../../redux/slices';
import { clearCreateFormAction, createPlaylistAction, setIsLoadingAction } from '../slices';
import { removeQueriesAction } from '@/modules/@common/location/redux/slices';
import { gqlRequest } from '@/modules/@common/request';
import { getToken } from '@/modules/@common/token/helpers';
import {
  frequencySelector,
  hubSelector,
  includeSponsoredContentSelector,
  isPrefixSelector,
  nameSelector,
  playerSelector,
  shuffleSelector,
  statusSelector,
  supplyTagSelector,
  urlSelector,
} from '@/modules/editorial/RightSideBar/TabPlaylist/Edit/redux/selectors';

const queryGQL = `
  mutation createPlaylist(
    $playerId: [Int!],
    $status: Boolean!,
    $isPrefix: Boolean!,
    $name: String!,
    $url: String,
    $publisherId: Int!,
    $clips: [String],
    $type: String,
    $shuffle: Boolean,
    $includeSponsoredContent: Boolean,
    $frequency: Int,
    $supplyTagId: String,
    $supplyTagName: String,
  ) {
    createPlaylist(
      playerId: $playerId,
      status: $status,
      isPrefix: $isPrefix,
      name: $name,
      url: $url,
      publisherId: $publisherId,
      clips: $clips,
      type: $type,
      shuffle: $shuffle,
      includeSponsoredContent: $includeSponsoredContent,
      frequency: $frequency,
      supplyTagId: $supplyTagId,
      supplyTagName: $supplyTagName,
    ) {
      playlistId
    }
  }
`;

export default (action$, state$) =>
  action$.pipe(
    ofType(createPlaylistAction.type),
    filter(() => !!getToken()),
    switchMap(() => {
      const hub = hubSelector(state$.value);
      const name = nameSelector(state$.value);
      const status = statusSelector(state$.value);
      const url = urlSelector(state$.value);
      const playerId = playerSelector(state$.value).id;
      const isPrefix = isPrefixSelector(state$.value);
      const shuffle = shuffleSelector(state$.value);

      const includeSponsoredContent = includeSponsoredContentSelector(state$.value);
      const frequency = parseInt(frequencySelector(state$.value), 10);
      const supplyTagId = supplyTagSelector(state$.value)?.id;
      const supplyTagName = supplyTagSelector(state$.value)?.name;

      const clips = [];

      const params = {
        publisherId: hub.value,
        name,
        status,
        playerId,
        isPrefix,
        shuffle,
        clips,
        type: PLAYLIST_TYPE,

        includeSponsoredContent,
        frequency,
        supplyTagId,
        supplyTagName,
      };
      if (url) {
        params.url = url;
      }

      const stream$ = gqlRequest({
        query: queryGQL,
        variables: params,
      }).pipe(
        mergeMap(({ data, errors }) => {
          const actions = [];

          if (!errors.length) {
            actions.push(
              of(clearCreateFormAction()),
              of(removeQueriesAction([QUERY_PARAM_PLAYLIST])),
              of(getPlaylistByIdAction({ id: data.createPlaylist.playlistId })),
            );
          }

          return concat(...actions);
        }),
      );

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