import { CONDITION_ENUM_AND, RULE_TYPE_SOURCES, SHARE_WITH_TYPE_HUBS } from '../constants';

const getRulesAction = (rules, shouldAddCondition) => {
  const res = [];

  Object.keys(rules).forEach((ruleType) => {
    const rule = rules[ruleType];

    if (rule) {
      const ruleToState = {
        type: ruleType,
        value: [RULE_TYPE_SOURCES, SHARE_WITH_TYPE_HUBS].includes(ruleType)
          ? rule.value.map((o) => ({ label: o.name, value: o.id }))
          : rule.value,
      };

      if (shouldAddCondition) {
        ruleToState.condition = rule.condition || CONDITION_ENUM_AND;
      }

      res[rule.order] = ruleToState;
    }
  });

  return res.filter((o) => o);
};

const parseResponseToState = (response) => {
  const rules = response.map((rule) => {
    const ruleSelectType = getRulesAction(rule.sharedVideoRules, true);
    const ruleShareWithType = getRulesAction(rule.shareWith);
    const entity = {
      ruleId: rule.id,
      ruleName: rule.ruleName,
      ruleOrder: rule.ruleOrder,
      ruleSelectType,
      ruleShareWithType,
      initialFromApi: {
        ruleName: rule.ruleName,
        ruleSelectType,
        ruleShareWithType,
      },
      // options
      sourcesOptions: null,
      hubsOptions: null,
      usersOptions: null,
      // ui state
      uiIndex: `${Math.random()}-${Math.random()}`,
      uiIsOpen: true,
      uiIsSaved: true,
      uiIsNameInEditMode: false,
    };

    return entity;
  });

  return rules;
};

export default parseResponseToState;
