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

import { CALENDAR_FILTER_VALUE } from '../../constants';
import {
  WIDGET_DISPLAY_STATE_DATA,
  WIDGET_DISPLAY_STATE_ERROR,
  WIDGET_DISPLAY_STATE_NO_DATA,
} from '@/modules/analytics/common/constants';

import * as selectors from '../selectors';
import { getPerformanceVideosTotalMetricAction, setFieldAction } from '../slices';
import { gqlRequest } from '@/modules/@common/request';
import { getUserTimezoneSelector } from '@/modules/@common/user/redux/selectors';

const query = `
  query PerformanceVideoTotalMetricQuery(
    $metric: String,
    $publisherId: Int,
    $watchId: Int,
    $channelId: Int,
    $origin: String,
    $dateRange: AnalyticsDateRangeInputType,
    $interval: String,
    $includeArchived: Boolean
  ) {
    performanceVideoTotalMetric(
      metric: $metric,
      publisherId: $publisherId,
      watchId: $watchId,
      channelId: $channelId,
      origin: $origin,
      dateRange: $dateRange,
      interval: $interval,
      includeArchived: $includeArchived
    ) {
      data {
        time
        value
      }
      rid
    }
  }
`;

export default (action$, state$) =>
  action$.pipe(
    ofType(getPerformanceVideosTotalMetricAction.type),
    mergeMap(({ payload: { metric, key } }) => {
      const state = state$.value;

      const hub = selectors.hubSelector(state);
      const watch = selectors.watchSelector(state);
      const watchChannel = selectors.watchChannelSelector(state);
      const origin = selectors.originSelector(state);
      const calendar = selectors.calendarSelector(state);
      const calendarCustom = selectors.calendarCustomSelector(state);
      const includeArchived = selectors.includeArchivedSelector(state);

      const { comparison, interval, videoChartDataKey, ...dateRange } = calendar;

      let filters = {};
      const timezone = getUserTimezoneSelector(state$.value);

      if (hub) {
        filters = {
          ...filters,
          publisherId: hub.value,
        };
      }

      if (watch) {
        filters = {
          ...filters,
          watchId: watch.value,
        };
      }

      if (watchChannel) {
        filters = {
          ...filters,
          channelId: watchChannel.value,
        };
      }

      if (origin !== 'ALL') {
        filters = {
          ...filters,
          origin,
        };
      }

      if (calendar === CALENDAR_FILTER_VALUE.custom) {
        filters = {
          ...filters,
          dateRange: {
            stringFrom: calendarCustom.dateStart,
            stringTo: calendarCustom.dateEnd,
            timezone,
          },
          interval: calendarCustom.interval,
        };
      } else {
        filters = {
          ...filters,
          dateRange: {
            ...dateRange,
            timezone,
          },
          interval,
        };
      }

      const stream$ = gqlRequest({
        query,
        variables: {
          includeArchived,
          metric,
          ...filters,
        },
      }).pipe(
        switchMap(({ data: { performanceVideoTotalMetric }, errors }) => {
          const actions = [];

          if (!errors.length) {
            actions.push(
              of(
                setFieldAction({
                  [key]: performanceVideoTotalMetric.data,
                  displayStateMainMetrics: performanceVideoTotalMetric.data?.length
                    ? WIDGET_DISPLAY_STATE_DATA
                    : WIDGET_DISPLAY_STATE_NO_DATA,
                }),
              ),
            );
          } else {
            actions.push(
              of(
                setFieldAction({
                  displayStateMainMetrics: WIDGET_DISPLAY_STATE_ERROR,
                }),
              ),
            );
          }

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

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