import { typeof as _typeof } from '../../../_virtual/_rollupPluginBabelHelpers.js';
import { deepCopy } from '../../../utils/deepCopy.js';

// Утилита для поиска ключа в объекте по пути.
var keyExists = function keyExists(obj, path) {
  if (_typeof(obj) !== 'object' || obj === null || !Array.isArray(path)) {
    return false;
  }
  var current = obj;
  for (var i = 0; i < path.length; i++) {
    var _key = path[i];
    if (current === null || _typeof(current) !== 'object' || !(_key in current)) {
      return false;
    }
    current = current[_key];
  }
  return true;
};
function createObjectAtPath(obj, path) {
  if (_typeof(obj) !== 'object' || obj === null) {
    return;
  }
  var current = obj;
  for (var i = 0; i < path.length; i++) {
    var _key2 = path[i];
    if (i === path.length - 1) {
      current[_key2] = {};
      break;
    }
    if (current[_key2] === undefined || current[_key2] === null) {
      current[_key2] = {};
    }
    current = current[_key2];
  }
  return obj;
}
function removeObjectAtPath(obj, path) {
  if (path.length === 0) {
    return obj;
  }
  var current = obj;
  for (var i = 0; i < path.length; i++) {
    var _key3 = path[i];
    if (current === null || _typeof(current) !== 'object' || !(_key3 in current)) {
      return obj;
    }
    if (i === path.length - 1) {
      delete current[_key3];
      break;
    }
    current = current[_key3];
  }
  return obj;
}
function treePathReducer(state, action) {
  switch (action.type) {
    case 'reset':
      {
        return {};
      }
    case 'toggled_level':
      {
        var stateCopy = deepCopy(state);
        var isTargetLevelOpened = keyExists(stateCopy, action.value);
        if (isTargetLevelOpened) {
          // нужно закрыть текущий уровень
          removeObjectAtPath(stateCopy, action.value);
        } else {
          // нужно открыть требуемый уровень
          createObjectAtPath(stateCopy, action.value);
        }
        return stateCopy;
      }
    case 'open_level':
      {
        var _stateCopy = deepCopy(state);
        createObjectAtPath(_stateCopy, action.value);
        return _stateCopy;
      }
    case 'close_level':
      {
        var _stateCopy2 = deepCopy(state);
        removeObjectAtPath(_stateCopy2, action.value);
        return _stateCopy2;
      }
    default:
      {
        return state;
      }
  }
}

export { keyExists, treePathReducer };
