import {
  RULE_TYPE_ALL_MY_VIDEO,
  RULE_TYPE_LABELS,
  RULE_TYPE_SOURCES,
  RULE_TYPE_WORDS_IN_TITLE,
  SHARE_WITH_TYPE_ALL_RELATED_USERS,
  SHARE_WITH_TYPE_HUBS,
  SHARE_WITH_TYPE_USERS,
} from '../constants';

import { rulesSelector } from '@/modules/userRulesSettings/redux/selectors';

const mapToId = (o) => ({ id: o.value });

const getSharedVideoRules = (ruleSelectType) => {
  const rules = {};

  ruleSelectType.forEach((rule, ruleIndex) => {
    rules[rule.type] = {
      order: ruleIndex,
      condition: rule.condition,
    };

    if (rule.type === RULE_TYPE_ALL_MY_VIDEO) {
      rules[rule.type].value = true;
    }

    if ([RULE_TYPE_LABELS, RULE_TYPE_WORDS_IN_TITLE].includes(rule.type)) {
      rules[rule.type].value = rule.value;
    }

    if (rule.type === RULE_TYPE_SOURCES) {
      rules[rule.type].value = rule.value.map(mapToId);
    }
  });

  return Object.keys(rules).length ? rules : null;
};

const getShareWithRules = (shareWithType) => {
  const rules = {};

  shareWithType.forEach((rule, ruleIndex) => {
    if (rule.type === SHARE_WITH_TYPE_ALL_RELATED_USERS) {
      rules[rule.type] = { value: true, order: ruleIndex };
    }

    if (rule.type === SHARE_WITH_TYPE_HUBS) {
      rules[rule.type] = { value: rule.value.map(mapToId), order: ruleIndex };
    }

    if (rule.type === SHARE_WITH_TYPE_USERS) {
      rules[rule.type] = { value: rule.value, order: ruleIndex };
    }
  });

  return Object.keys(rules).length ? rules : null;
};

const createRequestBodyFromState = (state) => {
  const rules = rulesSelector(state);

  const body = rules
    .filter((rule) => rule.initialFromApi)
    .map((rule, ruleIndex) => {
      const result = {
        ruleName: rule.uiIsSaved ? rule.ruleName : rule.initialFromApi.ruleName,
        ruleOrder: ruleIndex,
      };
      const sharedVideoRules = getSharedVideoRules(
        rule.uiIsSaved ? rule.ruleSelectType : rule.initialFromApi.ruleSelectType,
      );
      const shareWith = getShareWithRules(
        rule.uiIsSaved ? rule.ruleShareWithType : rule.initialFromApi.ruleShareWithType,
      );

      if (sharedVideoRules) {
        result.sharedVideoRules = sharedVideoRules;
      }

      if (shareWith) {
        result.shareWith = shareWith;
      }

      return result;
    });

  return body;
};

export default createRequestBodyFromState;
