import { defineStore } from 'pinia';
import { ref } from 'vue';

export const useElementsInfoStore = defineStore('elementsInfo', () => {
  const elements = ref<any[]>([]);
  function updateElement(elementId: string, info: any) {
    const index = elements.value.findIndex(item => item.id === elementId);
    if (index !== -1) {
      elements.value[index] = { ...elements.value[index], ...info };
    }
    else {
      elements.value.push({ id: elementId, ...info });
    }
  }

  function getElementById(elementId: string) {
    return elements.value.find(item => item.id === elementId);
  }

  function deleteElement(elementId: string) {
    const index = elements.value.findIndex(item => item.id === elementId);
    if (index !== -1) {
      elements.value.splice(index, 1);
    }
  }

  function clearElements() {
    elements.value = [];
  }

  function editFlowName(name: string) {
    const index = elements.value.findIndex(item => item.type === 'flow');
    if (index >= 0) {
      const flow = elements.value.find(item => item.type === 'flow');
      if (flow) {
        flow.title = name;
        elements.value[index] = { ...flow };
      }
    }
  }

  function editFlowId(id: string) {
    const index = elements.value.findIndex(item => item.type === 'flow');
    if (index >= 0) {
      const flow = elements.value.find(item => item.type === 'flow');
      if (flow) {
        flow.id = id;
        elements.value[index] = { ...flow };
      }
    }
  }
  return { elements, updateElement, getElementById, deleteElement, clearElements, editFlowName, editFlowId };
});
