import { ofType } from 'redux-observable';
import { concat, of } from 'rxjs';
import { 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 { getPerformanceVideosTotalAction, setFieldAction } from '../slices';
import { gqlRequest } from '@/modules/@common/request';
import { getUserTimezoneSelector } from '@/modules/@common/user/redux/selectors';

const query = `
  query PerformanceVideosTotalQuery(
    $publisherId: Int,
    $watchId: Int,
    $channelId: Int,
    $origin: String,
    $dateRange: AnalyticsDateRangeInputType,
    $dateRangeComparison: AnalyticsDateRangeInputType,
    $includeArchived: Boolean
  ) {
    performanceVideoTotal(
      publisherId: $publisherId,
      watchId: $watchId,
      channelId: $channelId,
      origin: $origin,
      dateRange: $dateRange,
      dateRangeComparison: $dateRangeComparison,
      includeArchived: $includeArchived
    ) {
      metrics {
        total {
          numOfViews
          attentionSpan
          engScore
          searches
        }
        comparison {
          numOfViews
          attentionSpan
          engScore
          searches
        }
        hideComparisonNumbers
      }
      rid
    }
  }
`;

export default (action$, state$) =>
  action$.pipe(
    ofType(getPerformanceVideosTotalAction.type),
    switchMap(() => {
      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,
          },
          dateRangeComparison: {
            stringFrom: calendarCustom.comparison.dateStart,
            stringTo: calendarCustom.comparison.dateEnd,
            timezone,
          },
        };
      } else {
        filters = {
          ...filters,
          dateRange: {
            ...dateRange,
            timezone,
          },
          dateRangeComparison: {
            ...comparison,
            timezone,
          },
        };
      }

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

          if (!errors.length && data?.performanceVideoTotal?.metrics) {
            actions.push(
              of(
                setFieldAction({
                  metrics: data.performanceVideoTotal.metrics,
                  displayStateMainMetrics:
                    data.performanceVideoTotal.metrics?.total?.numOfViews !== null ||
                    data.performanceVideoTotal.metrics?.total?.attentionSpan !== null ||
                    data.performanceVideoTotal.metrics?.total?.engScore !== null ||
                    data.performanceVideoTotal.metrics?.total?.searches !== null
                      ? 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$);
    }),
  );
