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

import { getStreamData } from '../../helpers/request';
import { setIsLoadingAction, slice, updateLiveEventAction, updateLiveStreamAction } from '../slices';
import { gqlRequest } from '@/modules/@common/request';

const queryGQL = `
  mutation updateLiveStream(
    $id: String!,
    $name: String!,
    $url: String,
    $description: String,
    $schedules: [LiveEventSchedulesInputType]!,
    $region: String,
    $recurrent: Boolean,
    $recurrentPeriod: String,
    $timeZone: String,
    $recurrentEndDate: Float,
  ) {
    updateLiveStream(
      id: $id,
      name: $name,
      url: $url,
      description: $description,
      schedules: $schedules,
      region: $region,
      recurrent: $recurrent,
      recurrentPeriod: $recurrentPeriod,
      timeZone: $timeZone,
      recurrentEndDate: $recurrentEndDate,
    ) {
      uid,
      name,
      url,
      description,
      schedules {
        id
        title
        startTime
        endTime
        durationIn
      }
      delivery,
      region,
      status,
      recurrent,
      recurrentPeriod,
      timeZone,
      recurrentEndDate,
    }
  }
`;

export default (action$, state$) =>
  action$.pipe(
    ofType(updateLiveStreamAction.type),
    switchMap(() => {
      const data = getStreamData(state$.value[slice.name]);
      const stream$ = gqlRequest({
        query: queryGQL,
        variables: {
          ...data,
        },
      }).pipe(
        switchMap(({ errors }) => {
          const actions = [of(setIsLoadingAction(false))];

          if (!errors.length) {
            actions.push(of(updateLiveEventAction()));
          }

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

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