import { ofType } from 'redux-observable';
import { concat, defer, EMPTY } from 'rxjs';
import { ajax } from 'rxjs/ajax';
import { switchMap } from 'rxjs/operators';

import {
  DEFAULT_VERIFICATION_TYPE_VALUE,
  DEFAULT_VIDEO_STATUS_VALUE,
} from '@/modules/editorial/editorialSearchFilter/constants';

import { getClosestKnownTimeZone, getOriginValue } from '../../helpers';
import { getToken } from '@/modules/@common/token/helpers';
import { fromSuggesterSelector, querySelector } from '@/modules/editorial/editorialSearch/reduxSearch/selectors';
import { filterInternalParamsSelector } from '@/modules/editorial/editorialSearchResults/redux/selectors';
import { downloadEventAction } from '@/modules/editorial/editorialSearchResults/redux/slices';

export default (action$, state$) =>
  action$.pipe(
    ofType(downloadEventAction.type),
    switchMap(() => {
      const state = state$.value;
      const query = querySelector(state);
      const fromSuggester = fromSuggesterSelector(state);
      const filterInternalParams = filterInternalParamsSelector(state);
      const body = {
        ...filterInternalParams,
        queryIds: true,
        typeValue: 'SHORT_FORM',
        timeZone: getClosestKnownTimeZone(),
        includeMaxPerformance: true,
      };

      body.origins = getOriginValue(filterInternalParams);

      if (filterInternalParams.status && filterInternalParams.status !== DEFAULT_VIDEO_STATUS_VALUE) {
        body.stateValue = filterInternalParams.status;
      }

      if (filterInternalParams.verification && filterInternalParams.verification !== DEFAULT_VERIFICATION_TYPE_VALUE) {
        body.verificationValue = filterInternalParams.verification;
      }

      if (filterInternalParams.account?.[0]?.owners?.length) {
        body.owners = filterInternalParams.account[0].owners.map((o) => o.toString());
        delete body.account;
      }

      if (query.length) {
        body.query = query;

        if (fromSuggester) {
          body.names = [query];
        }
      }

      body.fromEditorial = true;

      const request = () =>
        ajax({
          method: 'POST',
          url: '/api/export/video-list',
          headers: {
            'Content-Type': 'application/json',
            Authorization: getToken(),
          },
          responseType: 'blob',
          body,
        });

      const stream$ = defer(() => request()).pipe(
        switchMap(({ response }) => {
          const url = window.URL.createObjectURL(new Blob([response]));
          const link = document.createElement('a');

          link.href = url;
          link.setAttribute('download', 'export_search_list.xlsx');
          document.body.appendChild(link);
          link.click();

          return EMPTY;
        }),
      );

      return concat(stream$);
    }),
  );
