import { ofType } from 'redux-observable';
import { map } from 'rxjs/operators';

import { PCN_PUT_PLAYLIST } from '@/modules/@common/acl/constants';
import { MODE_PLAYLIST } from '@/modules/editorial/RightSideBar/common/constants';

import { canAddToPlaylistAction } from '../slices';
import { hasPermission } from '@/modules/@common/user/helpers';
import { getUserPermissionsSelector } from '@/modules/@common/user/redux/selectors';
import { modeSelector } from '@/modules/editorial/RightSideBar/TabPlaylist/redux/selectors';
import { setModeAction } from '@/modules/editorial/RightSideBar/TabPlaylist/redux/slices';
import * as watchesSelectors from '@/modules/editorial/RightSideBar/TabWatch/Watches/redux/selectors';
import { openChannelAction } from '@/modules/editorial/RightSideBar/TabWatch/Watches/redux/slices';

export default (action$, state$) =>
  action$.pipe(
    ofType(setModeAction.type, openChannelAction.type),
    map(({ type }) => {
      const userPermissions = getUserPermissionsSelector(state$.value);
      const mode = modeSelector(state$.value);
      const canAddToPlaylist =
        type === openChannelAction.type
          ? !!watchesSelectors.channelIdSelector(state$.value)
          : mode === MODE_PLAYLIST && hasPermission(PCN_PUT_PLAYLIST, userPermissions);

      return canAddToPlaylistAction(canAddToPlaylist);
    }),
  );
