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

import { TYPE_ERROR } from '@/modules/@common/notify/constants';
import { PLAYLIST_TYPE } from '@/modules/editorial/RightSideBar/TabPlaylist/Edit/constants';

import { getPlaylistByIdAction, updateStoreByPropAction } from '../slices';
import { gqlRequest } from '@/modules/@common/request';
import { getToken } from '@/modules/@common/token/helpers';
import { showNotificationAction } from '@/modules/layout/redux/slices';

const queryGQL = `
  query getPlaylistById(
    $id: Int!,
  ) {
    getPlaylistById(
      id: $id,
    ) {
      id
      playerId
      status
      isPrefix
      name
      url
      createdAt
      updatedAt
      createdBy
      updatedBy
      clips
      shuffle
      playerAlias
      widgetName
      pubName
      publisherId
      publisherName
      playerAspectRatio
      type
      isFallback
      includeSponsoredContent,
      frequency,
      supplyTagId,
      supplyTagName,
    }
  }
`;

export default (action$) =>
  action$.pipe(
    ofType(getPlaylistByIdAction.type),
    filter(() => !!getToken()),
    concatMap(({ payload }) =>
      gqlRequest({
        query: queryGQL,
        variables: {
          id: payload,
        },
      }).pipe(
        switchMap(({ data, errors }) => {
          const actions = [];

          if (!errors.length) {
            if (data.getPlaylistById.type !== PLAYLIST_TYPE) {
              return of(
                showNotificationAction({
                  type: TYPE_ERROR,
                  message: `Playlist ${data.getPlaylistById.id} doesn't exist`,
                }),
              );
            }

            const selectedPlayer = {
              value: data.getPlaylistById.playerId,
              label: data.getPlaylistById.playerAlias,
              urlPrefix: [data.getPlaylistById.url],
            };

            actions.push(
              of(
                updateStoreByPropAction({
                  ...data.getPlaylistById,
                  playlistId: data.getPlaylistById.id,
                  hub: {
                    value: data.getPlaylistById.publisherId,
                    label: data.getPlaylistById.publisherName,
                  },
                  player: selectedPlayer,
                  playerOptions: [selectedPlayer],
                  supplyTag: {
                    id: data.getPlaylistById.supplyTagId,
                    name: data.getPlaylistById.supplyTagName,
                  },
                }),
              ),
            );
          }

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