const state = {
  openDialogs: []
};

const getters = {
  openDialogs: (state) => state.openDialogs
};

let minimizing = false;
const mutations = {
  addOpenDialog(state, dialog) {
    if (!state.openDialogs.find((d) => d.dialog.name === dialog.dialog.name)) {
      state.openDialogs.push(dialog);
    }
    state.openDialogs.forEach((dlg) => {
      dlg.dialog.setActiveState(false);
    });
    dialog.dialog.setActiveState(true);
  },
  removeOpenDialog(state, dialogName) {
    state.openDialogs = state.openDialogs.filter((dialog) => dialog.dialog.name !== dialogName);
    let activeIsSet = false;
    state.openDialogs.forEach((dialog) => {
      if (!dialog.dialog.isMinimized() && !activeIsSet) {
        dialog.dialog.setActiveState(true);
        activeIsSet = true;
      }
    });
  },
  toggleDialogMinimize(state, dialogName) {
    if (minimizing) {
      return;
    }
    minimizing = true;
    const dialog = state.openDialogs.find((dialog) => dialog.dialog.name === dialogName);
    if (dialog) {
      dialog.dialog.toggleMinimize();
    }
    minimizing = false;
  },
  updateDialogTitle(state, { name, newTitle, isTitleTranslated }) {
    const dialogIndex = state.openDialogs.findIndex((d) => d.dialog.name === name);
    if (dialogIndex !== -1) {
      const updatedDialog = {
        ...state.openDialogs[dialogIndex],
        dialog: {
          ...state.openDialogs[dialogIndex].dialog,
          localTitle: newTitle,
          isTitleTranslated: isTitleTranslated
        }
      };
      state.openDialogs.splice(dialogIndex, 1, updatedDialog);
    }
  }
};

const actions = {
  addOpenDialog({ commit }, dialog) {
    commit('addOpenDialog', dialog);
  },
  removeOpenDialog({ commit }, dialogName) {
    commit('removeOpenDialog', dialogName);
  },
  toggleDialogMinimize({ commit }, dialogName) {
    commit('toggleDialogMinimize', dialogName);
  },
  updateDialogTitle({ commit }, { name, newTitle, isTitleTranslated }) {
    commit('updateDialogTitle', { name, newTitle, isTitleTranslated });
  },
};

export default {
  namespaced: true,
  state,
  getters,
  mutations,
  actions
};
