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

import { setDefaultPropsFromWatchAction, updateStoreByPropAction } from '../slices';
import { gqlRequest } from '@/modules/@common/request';

const queryGQL = `
  query WatchQuery($id: Int!) {
    watch(id: $id){
      id
      folderName
      environment
      appearance
      title
      bg
      fontSize
      color
      cTitleSize
      cTitleColor
      cDescSize
      cDescColor
      cVidTitleSize
      cVidTitleColor
      cInfoColor
      updatedBy
      updatedAt
      createdBy
      createdAt
      description
      player {
        id
        name
        alias
        publisherId
      }
      publisher {
        id
        name
      }
    }
  }
`;

export default (action$) =>
  action$.pipe(
    ofType(setDefaultPropsFromWatchAction.type),
    switchMap(({ payload }) => {
      const stream$ = gqlRequest({
        query: queryGQL,
        variables: {
          id: payload.watchId,
        },
      }).pipe(
        mergeMap(({ data, errors }) => {
          const actions = [];

          if (!errors.length) {
            const resultData = {
              appearance: data.watch.appearance,
              watchTitle: data.watch.title,
              watchEnvironment: data.watch.environment,
              watchFolderName: data.watch.folderName,
              watchHub: data.watch.publisher,
            };

            if (payload.newChannel) {
              resultData.titleColor = data.watch.cTitleColor;
              resultData.descColor = data.watch.cDescColor;
              resultData.vidTitleColor = data.watch.cVidTitleColor;
              resultData.vidInfoColor = data.watch.cInfoColor;
            }

            actions.push(of(updateStoreByPropAction(resultData)));
          }

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

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