"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.default = void 0;

var _beedle = _interopRequireDefault(require("beedle"));

var _requests = require("./requests");

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

let _saveUrl;

let _onPost;

let _onLoad;

const store = new _beedle.default({
  actions: {
    setData(context, data, saveData) {
      context.commit('setData', data);
      if (saveData) this.save(data);
    },

    load(context, {
      loadUrl,
      saveUrl,
      data
    }) {
      _saveUrl = saveUrl;

      if (_onLoad) {
        _onLoad().then(x => this.setData(context, x));
      } else if (loadUrl) {
        (0, _requests.get)(loadUrl).then(x => {
          if (data && data.length > 0 && x.length === 0) {
            data.forEach(y => x.push(y));
          }

          this.setData(context, x);
        });
      } else {
        this.setData(context, data);
      }
    },

    create(context, element) {
      const {
        data
      } = context.state;
      data.push(element);
      this.setData(context, data, true);
    },

    delete(context, element) {
      const {
        data
      } = context.state;
      data.splice(data.indexOf(element), 1);
      this.setData(context, data, true);
    },

    updateOrder(context, elements) {
      const newData = elements.filter(x => x && !x.parentId);
      elements.filter(x => x && x.parentId).forEach(x => newData.push(x)); // console.log('setAsChild', newData);

      this.setData(context, newData, true);
    },

    save(data) {
      if (_onPost) {
        _onPost({
          task_data: data
        });
      } else if (_saveUrl) {
        (0, _requests.post)(_saveUrl, {
          task_data: data
        });
      }
    },

    saveRootURL(context, data) {
      context.commit('setRootURL', data);
    },

    saveUser(context, data) {
      context.commit('setUser', data);
    },

    saveTranslate(context, data) {
      context.commit('setTranslate', data);
    }

  },
  mutations: {
    setData(state, payload) {
      // eslint-disable-next-line no-param-reassign
      state.data = payload;
      return state;
    },

    setRootURL(state, payload) {
      state.rootURL = payload;
      return state;
    },

    setUser(state, payload) {
      state.currentUser = payload;
      return state;
    },

    setTranslate(state, payload) {
      state.translate = payload;
      return state;
    }

  },
  initialState: {
    data: [],
    rootURL: "",
    currentUser: 0,
    translate: {}
  }
});

store.setExternalHandler = (onLoad, onPost) => {
  _onLoad = onLoad;
  _onPost = onPost;
};

var _default = store;
exports.default = _default;