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

import { getStreamData } from '../../helpers/request';
import {
  createLiveEventAction,
  createLiveStreamAction,
  setIsLoadingAction,
  slice,
  updateLiveEventFormAction,
} from '../slices';
import { gqlRequest } from '@/modules/@common/request';

const queryGQL = `
  mutation createLiveStream(
    $name: String!,
    $contentOwner: Int!,
    $description: String,
    $schedules: [LiveEventSchedulesInputType]!,
    $delivery: String!,
    $region: String,
    $url: String,
    $publisherId: Int!,
    $feedId: Int!,
    $liveCcEnabled: Boolean,
    $liveCcLang: String,
    $recurrent: Boolean,
    $recurrentPeriod: String,
    $recurrentEndDate: Float,
    $timeZone: String,
  ) {
    createLiveStream(
      name: $name,
      contentOwner: $contentOwner,
      description: $description,
      schedules: $schedules,
      delivery: $delivery,
      region: $region,
      url: $url,
      publisherId: $publisherId,
      feedId: $feedId,
      liveCcEnabled: $liveCcEnabled,
      liveCcLang: $liveCcLang,
      recurrent: $recurrent,
      recurrentPeriod: $recurrentPeriod,
      recurrentEndDate: $recurrentEndDate,
      timeZone: $timeZone,
    ) {
      uid,
      name,
      url,
      contentOwner,
      description,
      rtmpInputUrl,
      rtmpSecondaryInputUrl,
      rtmpStreamKey,
      rtmpSecondaryStreamKey,
      status,
      delivery,
      region,
      schedules {
        id
        title
        startTime
        endTime
        durationIn
      },
      liveCcEnabled,
      liveCcLang,
      recurrent,
      recurrentPeriod,
      recurrentEndDate,
      timeZone,
    }
  }
`;

export default (action$, state$) =>
  action$.pipe(
    ofType(createLiveStreamAction.type),
    switchMap((action) => {
      const body = getStreamData(state$.value[slice.name]);

      const stream$ = gqlRequest({
        query: queryGQL,
        variables: {
          ...action.payload,
          ...body,
        },
      }).pipe(
        concatMap(({ data, errors }) => {
          const actions = [of(setIsLoadingAction(false))];

          if (!errors.length) {
            const { uid } = data.createLiveStream;

            actions.push(
              of(
                updateLiveEventFormAction({
                  streamId: uid,
                }),
              ),
              of(
                createLiveEventAction({
                  streamId: uid,
                }),
              ),
            );
          }

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

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