import { RULE_TYPE_ALL_MY_VIDEO, SHARE_WITH_TYPE_ALL_RELATED_USERS } from '../constants';

import * as userRuleSettingsSelectors from '@/modules/userRulesSettings/redux/selectors';

export const rulesBySearch = (state$) => {
  const rules$ = userRuleSettingsSelectors.rulesSelector(state$);
  const search$ = userRuleSettingsSelectors.searchSelector(state$);

  if (!search$) {
    return rules$;
  }

  return rules$.filter((o) => o.ruleName?.toLowerCase().includes(search$.toLowerCase()));
};

export const shouldShowDuplicateNameError = (state$) => {
  const rules$ = userRuleSettingsSelectors.rulesSelector(state$);

  const normalize = (str) => str.replace(/\s+/g, '');
  return (name, isSaved, uiIndex) => {
    const rules = rules$.filter(
      (rule) => uiIndex !== rule.uiIndex && !isSaved && normalize(name) === normalize(rule.ruleName),
    );

    return !!rules.length;
  };
};

export const shouldDisableCreateNewRule = (state$) => {
  const rules$ = userRuleSettingsSelectors.rulesSelector(state$);
  return rules$.some((rule) => !rule.initialFromApi);
};

export const shouldDisabledSave = (state$) => {
  const rules$ = userRuleSettingsSelectors.rulesSelector(state$);

  return (uiIndex) => {
    const rule = rules$.find((o) => o.uiIndex === uiIndex);
    const { ruleSelectType, ruleShareWithType } = rule;

    const hasValue = (o) =>
      [RULE_TYPE_ALL_MY_VIDEO, SHARE_WITH_TYPE_ALL_RELATED_USERS].includes(o.type) ? true : o.value?.length;

    return !(ruleSelectType.every(hasValue) && ruleShareWithType.every(hasValue));
  };
};

export const isDirty = (state$) => {
  const rules$ = userRuleSettingsSelectors.rulesSelector(state$);

  return (uiIndex) => {
    const rule = rules$.find((o) => o.uiIndex === uiIndex);
    const { ruleSelectType, ruleShareWithType, initialFromApi } = rule;
    const currentValueString = JSON.stringify({ ruleSelectType, ruleShareWithType });
    const initialFromApiString = JSON.stringify({
      ruleSelectType: initialFromApi?.ruleSelectType,
      ruleShareWithType: initialFromApi?.ruleShareWithType,
    });

    return currentValueString !== initialFromApiString || rule.ruleName !== initialFromApi.ruleName;
  };
};
