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

import { TYPE_ERROR } from '@/modules/@common/notify/constants';

import { getPlayerDataAction, setDefaultsAction, setPlayerIsLoadingAction } from '../slices';
import { gqlRequest } from '@/modules/@common/request';
import { showNotificationAction } from '@/modules/layout/redux/slices';

const playerQuery = `
  query getPlayerById(
    $id: Int!
  ) {
     getPlayerUiProps {
      autoplayOptions {
        id
        term
        termUi
        isDefault
      }
      autoplayDesktop
      autoplayMobile
      flowTermsOptions {
        id
        term
        termUi
        termUiSelfServe
      }
      flowTermId
      editorialEnabled
      editorialType
      playerFeedLanguages {
        lang
        name
      }
      feedLanguagesOptions {
        lang
        name
      }
      availableTemplatePlayers {
        id
        name
        order
      }
      brandSafetiesOptions {
      termId
      term
      termUi
      } 
      playerWidthUnitOptions {
        value
        label
        defaultWidth
        isDefault
      }
      playerWidthUnit
      playerWidthMobileUnit
      playerAspectRatioOptions {
        value
        label
        isDefault
        withCarousel
        isDefaultForVertical
      }
      playerDynamicAspectRatioOptions {
        value
        label
        isDefault
        withCarousel
        isDefaultForVertical
      }
      playerAspectRatio
      brandingLeft
      brandingRight
      brandingRightDefault
      floatingDesktopModeOptions {
        value
        label
        isDefault
        forOutstream
      }
      floatingDesktopMode
      floatingDesktopPositionOptions {
        value
        label
        isDefault
      }
      floatingDesktopPosition
      floatingMobileModeOptions {
        value
        label
        isDefault
        forOutstream
      }
      floatingMobileMode
      floatingMobilePositionOptions {
        value
        label
        isDefault
        isDefaultForPageWidth
      }
      floatingMobilePosition
      boostsTypesOptions {
        value
        label
        isDefault
        grouped
      }
      carouselEnabled
      carouselEnabledMobile
      carouselOrientationOptions {
        value
        label
        isDefault
      }
      carouselOrientation
      closedCaptioningOptions {
        value
        label
        isDefault
      }
      closedCaptioning
      videoResolutionControl
      playbackSpeedControl
      fullScreen
      chapteringMenuNavigation
      chapteringTimeline
      theaterMode
      ffRewind
      socialViewButton
      socialLikeButton
      xRayCampaignsEnabled
      leftBrandingColor
      leftBrandingSize
      leftBrandingSizeOptions
      progressBarColor
      timestampTooltipColor
      volumeBarColor
      settingsMenuHighlightColor
      floatingDesktopEnabledOptions {
        value
        label
        isDefault
      }
      floatingDesktopEnabled
      floatingDesktopWidth
      floatingDesktopWidthVertical
      floatingDesktopDelay
      floatingMobileEnabledOptions {
        value
        label
        isDefault
        forAmp
        forOutstream
        width
        dependentFieldsDefaults {
          delayCloseIconEnabledMobile
        }
      }
      floatingMobileEnabled
      delayCloseIconEnabledMobile
      floatingMobileWidth
      floatingMobileWidthVertical
      floatingMobileDelay
      useDefaultContentOwner
      allFeeds
      playerContentOwnerFeeds{
      id
      name
      }
      startWithSoundOptions{
      value
      label
      }
      startWithSound
      startWithSoundMobile
      playlistLimit
      playInLoopOptions {
        value
        label
        isDefault
      }
      loopPlaylist
      adsOnLoopOff
      verticalFullscreenTitleTimelineVisibility
      swipeAnimation
      swipeAnimationMaxVisits
      swipeAnimationDuration
      playInLoop
      shufflePlaylist
      clipAutomaticSkipOptions {
        enabled {
         defaultValue
        }
        clipAutomaticSkipTimeToPresent {
        defaultValue
        minValue
        maxValue
        }
        clipAutomaticSkipTimeToSkip {
        defaultValue
        minValue
        maxValue
        }
      }
      clipAutomaticSkipEnabled
      clipAutomaticSkipTimeToPresent
      clipAutomaticSkipTimeToSkip
      adManagerDesktop
      adManagerMobile
      clipNotInViewPlayAdsDesktop
      clipNotInViewPlayAdsMobile
      maxAdsPerClipChecked
      maxAdsPerClip
      maxAdsPerClipOptions
      firstAdRequestDelay
      preRollOptions  {
        enabled {
         defaultValue
        }
        preRollWaitMs {
        defaultValue
        minValue
        maxValue
        }
      }
      preRoll
      preRollWaitMs
      adIndicator
      adIndicatorText
      skipAdButton
      skipAdAppearAfter
      skipAdAppearAfterDefault
      inviewAdInterval
      notInviewAdInterval
      inviewAdIntervalMobile
      notInviewAdIntervalMobile
      displayMonetizationDesktop
      displayMonetizationMobile
      displayClipNotInViewPlayAdsDesktop
      displayClipNotInViewPlayAdsMobile
      displayInviewAdInterval
      displayNotInviewAdInterval
      displayInviewAdIntervalMobile
      displayNotInviewAdIntervalMobile
      abTest
      customPlaceholderEnable
      selectors {
        selector
      }
    }
    getPlayerById(
      id: $id
    ) {
      id
      type
      name
      status
      playerType {
        id
        name
        order
      }
      alias
      publisherDomainId
      comments
      publisherId
      publisher {
        id
        name
        includePublicContent
        monetization
        slug
        publisherDomains {
          id
          domain
        }
        publisherContentOwners {
          id
          contentOwnerId
        }                
      }
      playerLreLogo {
        file
        link
        enabled
      }
      playerWidth
      playerWidthUnit 
      playerWidthMobile
      playerWidthMobileUnit                        
      playerAspectRatio
      brandingLeft
      carouselEnabled
      carouselEnabledMobile
      carouselOrientation
      brandingRight
      closedCaptioning
      videoResolutionControl
      playbackSpeedControl
      fullScreen
      chapteringMenuNavigation
      chapteringTimeline
      theaterMode
      ffRewind
      socialViewButton
      socialLikeButton
      xRayCampaignsEnabled
      leftBrandingColor
      leftBrandingSize
      progressBarColor
      timestampTooltipColor
      volumeBarColor
      settingsMenuHighlightColor
      floatingDesktopEnabled
      floatingDesktopMode
      floatingDesktopPosition
      floatingDesktopWidth
      floatingDesktopDelay
      floatingMobileEnabled
      delayCloseIconEnabledMobile
      floatingMobileMode
      floatingMobilePosition
      floatingMobileWidth
      floatingMobileDelay
      useDefaultContentOwner
      playerFeedLanguages {
        id
        lang
        name
      }
      playerBrandSafeties {
        id
        termId
        term
        termUi
      }
      boosts {
        id
        type
        value
        score
      }
      allFeeds
      playerContentOwnerFeeds {
        id
        name
        description
        contentOwner {
          id
          name
          isPublic
        }
        playerContentOwnerFeedId
        accountId
      }
      autoplayDesktop
      autoplayMobile
      startWithSound
      startWithSoundMobile
      playlistLimit
      flowTermId
      editorialEnabled
      editorialType
      loopPlaylist
      adsOnLoopOff
      verticalFullscreenTitleTimelineVisibility
      swipeAnimation
      swipeAnimationMaxVisits
      swipeAnimationDuration
      playInLoop
      shufflePlaylist
      clipAutomaticSkipEnabled
      clipAutomaticSkipTimeToPresent
      clipAutomaticSkipTimeToSkip
      playerEditorialPlaylistId
      editorialPlaylist {
        id
        title
        clips {
          title
          mediaid
          image
          file
          hlsFile{
            file
          }
          files {
            width
            height
            file
          }
          images {
            width
            height
            file
          }
        }
      }
      adManagerDesktop
      fallbackDisplayMonetizationDesktop
      adManagerMobile
      fallbackDisplayMonetizationMobile
      clipNotInViewPlayAdsDesktop
      clipNotInViewPlayAdsMobile
      maxAdsPerClipChecked
      maxAdsPerClip
      firstAdRequestDelay
      preRoll
      preRollWaitMs
      prerollOnly
      prerollOnlyClipsCount
      adIndicator
      adIndicatorText
      skipAdButton
      skipAdAppearAfter
      inviewAdInterval
      notInviewAdInterval
      inviewAdIntervalMobile
      notInviewAdIntervalMobile
      displayMonetizationDesktop
      displayMonetizationMobile
      displayClipNotInViewPlayAdsDesktop
      displayClipNotInViewPlayAdsMobile
      displayInviewAdInterval
      displayNotInviewAdInterval
      displayInviewAdIntervalMobile
      displayNotInviewAdIntervalMobile
      abTest
      enableVideoTargeting
      videoFormatByDevice
      customPlaceholderEnable
      selectors {
        selector
        id
      }
    }
  }
`;

const defaultPropsQuery = `
  query getPlayerUiProps{
   getPlayerUiProps {
      autoplayOptions {
        id
        term
        termUi
        isDefault
      }
      autoplayDesktop
      autoplayMobile
      flowTermsOptions {
        id
        term
        termUi
        termUiSelfServe
      }
      flowTermId
      editorialEnabled
      editorialType
      feedLanguagesOptions {
        lang
        name
      }   
      playerFeedLanguages {
        lang
        name
      }
      availableTemplatePlayers {
        id
        name
        order
      }
      brandSafetiesOptions {
      termId
      term
      termUi
      } 
      playerWidthUnitOptions {
        value
        label
        defaultWidth
        isDefault
      }
      playerWidth
      playerWidthUnit
      playerWidthMobile
      playerWidthMobileUnit
      playerAspectRatioOptions {
        value
        label
        isDefault
        withCarousel
        isDefaultForVertical
      }
      playerDynamicAspectRatioOptions {
        value
        label
        isDefault
        withCarousel
        isDefaultForVertical
      }
      playerAspectRatio
      brandingLeft
      brandingRight
      brandingRightDefault
      floatingDesktopModeOptions {
        value
        label
        isDefault
        forOutstream
      }
      floatingDesktopMode
      floatingDesktopPositionOptions {
        value
        label
        isDefault
      }
      floatingDesktopPosition
      floatingMobileModeOptions {
        value
        label
        isDefault
        forOutstream
      }
      floatingMobileMode
      floatingMobilePositionOptions {
        value
        label
        isDefault
        isDefaultForPageWidth
      }
      floatingMobilePosition
      boostsTypesOptions {
        value
        label
        isDefault
        grouped
      }
      carouselEnabled
      carouselEnabledMobile
      carouselOrientationOptions {
        value
        label
        isDefault
      }
      carouselOrientation
      closedCaptioningOptions {
        value
        label
        isDefault
      }
      closedCaptioning
      videoResolutionControl
      playbackSpeedControl
      fullScreen
      chapteringMenuNavigation
      chapteringTimeline
      theaterMode
      ffRewind
      socialViewButton
      socialLikeButton
      xRayCampaignsEnabled
      leftBrandingColor
      leftBrandingSize
      leftBrandingSizeOptions
      progressBarColor
      timestampTooltipColor
      volumeBarColor
      settingsMenuHighlightColor
      floatingDesktopEnabledOptions {
        value
        label
        isDefault
      }
      floatingDesktopEnabled
      floatingDesktopWidth
      floatingDesktopWidthVertical
      floatingDesktopDelay
      floatingMobileEnabledOptions {
        value
        label
        isDefault
        forAmp
        forOutstream
        width
        dependentFieldsDefaults {
          delayCloseIconEnabledMobile
        }
      }
      floatingMobileEnabled
      delayCloseIconEnabledMobile
      floatingMobileWidth
      floatingMobileWidthVertical
      floatingMobileDelay
      useDefaultContentOwner
      allFeeds
      playerContentOwnerFeeds{
      id
      name
      }
      startWithSoundOptions{
      value
      label
      }
      startWithSound
      startWithSoundMobile
      playlistLimit
      playInLoopOptions {
        value
        label
        isDefault
      }
      loopPlaylist
      adsOnLoopOff
      verticalFullscreenTitleTimelineVisibility
      swipeAnimation
      swipeAnimationMaxVisits
      swipeAnimationDuration
      playInLoop
      shufflePlaylist
      clipAutomaticSkipOptions {
        enabled {
         defaultValue
        }
        clipAutomaticSkipTimeToPresent {
        defaultValue
        minValue
        maxValue
        }
        clipAutomaticSkipTimeToSkip {
        defaultValue
        minValue
        maxValue
        }
      }
      clipAutomaticSkipEnabled
      clipAutomaticSkipTimeToPresent
      clipAutomaticSkipTimeToSkip
      adManagerDesktop
      adManagerMobile
      clipNotInViewPlayAdsDesktop
      clipNotInViewPlayAdsMobile
      maxAdsPerClipChecked
      maxAdsPerClip
      maxAdsPerClipOptions
      firstAdRequestDelay
      preRollOptions  {
        enabled {
         defaultValue
        }
        preRollWaitMs {
        defaultValue
        minValue
        maxValue
        }
      }
      preRoll
      preRollWaitMs
      adIndicator
      adIndicatorText
      skipAdButton
      skipAdAppearAfter
      skipAdAppearAfterDefault
      inviewAdInterval
      notInviewAdInterval
      inviewAdIntervalMobile
      notInviewAdIntervalMobile
      displayMonetizationDesktop
      displayMonetizationMobile
      displayClipNotInViewPlayAdsDesktop
      displayClipNotInViewPlayAdsMobile
      displayInviewAdInterval
      displayNotInviewAdInterval
      displayInviewAdIntervalMobile
      displayNotInviewAdIntervalMobile
      abTest
      customPlaceholderEnable
      selectors {
        selector
        id
      }
    }
  }
`;

export default (action$) =>
  action$.pipe(
    ofType(getPlayerDataAction.type),
    switchMap((action) => {
      const variables = {};
      if (action.payload.id) {
        variables.id = action.payload.id;
      }
      const stream$ = gqlRequest({
        query: action.payload.id ? playerQuery : defaultPropsQuery,
        variables,
      }).pipe(
        switchMap((response) => {
          const actions = [];
          if (!response.errors.length) {
            const { getPlayerUiProps, getPlayerById } = response.data;

            if (getPlayerById) {
              if (action.payload.copy) {
                getPlayerById.alias = `Copy of ${getPlayerById.alias}`;
                getPlayerById.abTest = false;
              }
              getPlayerById.publisherDomainsOptions = getPlayerById.publisher.publisherDomains;
              getPlayerById.publisherDomain = getPlayerById.publisher.publisherDomains.find(
                (domain) => domain.id === getPlayerById.publisherDomainId,
              );
            }
            const state = {
              ...getPlayerUiProps,
              ...(action.payload.id && getPlayerById ? getPlayerById : {}),
            };

            actions.push(of(setDefaultsAction(state)));
          } else {
            actions.push(
              of(
                showNotificationAction({
                  type: TYPE_ERROR,
                  message: action.payload.id ? "Can't update Player" : "Can't create Player",
                }),
              ),
            );
          }
          return concat(...actions);
        }),
      );
      return concat(of(setPlayerIsLoadingAction(true)), stream$, of(setPlayerIsLoadingAction(false)));
    }),
  );
