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

import * as selectors from '../selectors';
import { getAdvertiserSettingsTabAction, setAdvertiserSettingsTabAction } from '../slices';

const getIncludeExcludeFromArray = (options, listInclude, listExclude) => {
  const includeExcludeList = [].concat(listInclude || [], listExclude || []);
  if (!includeExcludeList.length) {
    return [];
  }

  return includeExcludeList.map((item) => {
    let label = item[0].toUpperCase() + item.toLowerCase().substring(1);
    if (options && options.length) {
      const found = options.find((option) => option.value === item);
      if (found) {
        // eslint-disable-next-line prefer-destructuring
        label = found.label;
      }
    }
    return {
      label,
      value: item,
      include: listInclude ? listInclude.includes(item) : false,
    };
  });
};

export default (action$, state$) =>
  action$.pipe(
    ofType(getAdvertiserSettingsTabAction.type),
    switchMap(() => {
      const advertiserSettingsTab = {};
      const state = state$.value;

      const info = selectors.infoSelector(state);
      const advertiserSettings = selectors.advertiserSettingsSelector(state);

      if (info) {
        advertiserSettingsTab.countries = getIncludeExcludeFromArray(
          advertiserSettings?.countriesList,
          info.include?.geo,
          info.exclude?.geo,
        );

        if (info.tier) {
          advertiserSettingsTab.tier = info.tier;
        }

        if (info.name) {
          advertiserSettingsTab.name = info.name;
        }

        if (info.daccountId) {
          advertiserSettingsTab.demandAccountId = +info.daccountId;
        }

        if (info.revShare?.length) {
          advertiserSettingsTab.revShare =
            info.revShare?.map((price, index) => ({
              id: index,
              ...price,
            })) ?? [];
        }
        if (info.frequencyCapAdjustment !== null) {
          advertiserSettingsTab.frequencyCapAdjustment = info.frequencyCapAdjustment;
          advertiserSettingsTab.frequencyCapAdjustmentPerSupply = info.frequencyCapAdjustmentPerSupply;
        } else {
          advertiserSettingsTab.frequencyCapAdjustment = false;
        }

        if (info.frequencyCapAdjustment) {
          advertiserSettingsTab.frequencyCapAdjustmentThreshold = info.frequencyCapAdjustmentThreshold;
          advertiserSettingsTab.frequencyCapAdjustmentPerSupply = info.frequencyCapAdjustmentPerSupply;
        }

        if (info.logo) {
          advertiserSettingsTab.logo = info.logo;
        }

        advertiserSettingsTab.pbsEnabled = info.pbsEnabled;
        advertiserSettingsTab.profitability = info.profitability;
      }

      return concat(of(setAdvertiserSettingsTabAction(advertiserSettingsTab)));
    }),
  );
