import { defineStore } from "pinia";
import { DrawData, DrawItem, ShapeType } from '../components'

const sortFn = (a: Pick<DrawItem, 'zIndex' | 'createTime'>, b: Pick<DrawItem, 'zIndex' | 'createTime'>) => 
	a.zIndex - b.zIndex || a.createTime - b.createTime


export const useStoreRaw = defineStore('draw-data', {
	state: (): { data: DrawData, version: number } => ({ version: 0, data: {} }),
	getters: {
		items() {
			return Object.values((this as any).data).flat() as DrawItem[]
		},
		sortItems() {
			return (this.items as any).sort(sortFn) as DrawItem[]
		}
	},
	actions: {
		repStore(store: DrawData) {
			const newStore = JSON.parse(JSON.stringify(store))
			this.$patch({ data: newStore });
		},
		setStore(store: DrawData) {
			const newStore = JSON.parse(JSON.stringify(store))
			this.$patch({ version: 0, data: newStore });
		},
		getItemNdx<T extends ShapeType>(type: T, id: string) {
			const items = this.data[type]
			if (items) {
				return items.findIndex(item => item.id === id)
			}
			return -1
		},
		getItem<T extends ShapeType>(type: T, id: string) {
			const ndx = this.getItemNdx(type, id)
			if (~ndx) return this.data[type]![ndx]
		},
		addItems<T extends ShapeType>(type: T, items: DrawItem<T>[]) {
			console.log('add', items)
			items.forEach(item => this.addItem(type, item))
		},
		addItem<T extends ShapeType>(type: T, item: DrawItem<T>) {
			this.$patch((state) => {
				if (!(type in state.data)) {
					state.data[type] = []
				}
				state.data[type]!.push(item as any);
			})
		},
		delItem<T extends ShapeType>(type: T, id: string) {
			const ndx = this.getItemNdx(type, id)
			if (~ndx) {
				this.$patch(state => {
					state.data[type]!.splice(ndx, 1)
				})
			}
		},
		setItem<T extends ShapeType>(type: T, playData: { value: DrawItem<T>, id: string }) {
			const ndx = this.getItemNdx(type, playData.id)
			if (~ndx) {
				this.$patch(state => {
					Object.assign(state.data[type]![ndx], playData.value)
				})
			}
		},
		getItemsZIndex(items?: DrawItem[]) {
			if (!items) {
				return this.sortItems;
			} else {
				return items.sort(sortFn)
			}
		},
		getType(id: string) {
			const types = Object.keys(this.data) as ShapeType[]
			for (const type of types) {
				if (this.data[type]?.some(item=> item.id === id)) {
					return type
				}
			}
		},
		getItemById(id: string) {
			const types = Object.keys(this.data) as ShapeType[]
			for (const type of types) {
				const item = this.data[type]?.find(item=> item.id === id)
				if (item) {
					return item;
				}
			}
		}
	}
})
