import { fetchCategory } from './categories.js';
import { RULE_TYPE } from '../constants.js';
import { handleAPIError } from './error.js';

export const SELECT_RULE = 'SELECT_RULE';
export const SELECT_RULES = 'SELECT_RULES';

export const RECEIVE_RULE = 'RECEIVE_RULE';
export const RECEIVE_RULES = 'RECEIVE_RULES';

export const REQUEST_RULE = 'REQUEST_RULE';
export const REQUEST_RULES = 'REQUEST_RULES';

export const selectRule = rule => ({
  type: SELECT_RULE,
  section: { ...rule, type: RULE_TYPE },
});

export const requestRule = () => ({ type: REQUEST_RULE });
export const requestRules = () => ({ type: REQUEST_RULES });

export const receiveRule = rule => ({
  type: RECEIVE_RULE,
  rule,
});

export const receiveRules = rules => ({
  type: RECEIVE_RULES,
  rules,
});

export const fetchRule = rule => {
  return (dispatch, getState) => {
    const { selected } = getState();
    const selectedSection = { ...selected.item };

    if (selectedSection.type === RULE_TYPE && selectedSection.clicks <= 1) {
      return;
    }

    dispatch(requestRule());

    const { categories } = getState();
    const category = categories['items'][rule.category];

    return fetch(`/api/rules/${rule.id}`)
      .then(response => response.json())
      .then(receivedRule => {
        dispatch(receiveRule({ ...receivedRule }));

        // fetch & update category info when the rule is read
        if (rule.unread === 0) {
          return dispatch(fetchCategory({ ...category }));
        }
      })
      .catch(error => {
        dispatch(receiveRule({}));
        dispatch(handleAPIError(error));
      });
  };
};

export const fetchRulesByCategory = category => {
  return dispatch => {
    dispatch(requestRules());

    return fetch(`/api/categories/${category.id}/rules/`)
      .then(response => response.json())
      .then(rules => dispatch(receiveRules(rules)))
      .catch(error => {
        dispatch(receiveRules([]));
        dispatch(handleAPIError(error));
      });
  };
};
