import { defineStore } from 'pinia'
import { nanoid } from 'nanoid'

export interface State {
  materials: MaterialState[]
}

export interface MaterialState {
  id: string
  node1: string
  node2: string
  type: string
  style: string
  update_rule: string
  desc: string
}

export const useMaterialStore = defineStore('material', {
  state: (): State => {
    return {
      materials: []
    }
  },

  actions: {
    setData(data?: State) {
      if (!data?.materials) return
      this.setMaterials(data.materials)
    },
    setMaterials(list: MaterialState[]) {
      this.materials = list
    },
    addMaterial(data: Omit<MaterialState, 'id'>) {
      this.materials.push({ id: nanoid(4), ...data })
    },
    updateMaterial(data: MaterialState) {
      const index = this.materials.findIndex(item => item.id === data.id)
      this.materials[index] = data
    },
    removeMaterial(id: string) {
      this.materials = this.materials.filter(item => item.id !== id)
    }
  }
})
