import {StoryItem, TimelineEvent} from "@/pages/list/basic-list/data";
import {CommonConstant} from "@/commonConstant/commonConstant";


export function getTimelineItems(id: string): TimelineEvent[] {
  const itemsStr = localStorage.getItem(`timelineItems_${id}`);
  return itemsStr ? JSON.parse(itemsStr) : [];
}
export const updateTimelineItem = (
  lineId: string | number,
  updatedItem: TimelineEvent
) => {
  const key = `timelineItems_${lineId}`;
  const list = getTimelineItems(lineId);
  const index = list.findIndex((item: TimelineEvent) => item.id === updatedItem.id);
  if (index !== -1) {
    list[index] = updatedItem;
    localStorage.setItem(key, JSON.stringify(list));
  }
};

export const deleteTimelineItem = (
  lineId: string | number,
  itemId: number
) => {
  const key = `timelineItems_${lineId}`;
  const list = getTimelineItems(lineId);
  const filteredList = list.filter((item: TimelineEvent) => item.id !== itemId);
  localStorage.setItem(key, JSON.stringify(filteredList));
};

export const handleStoryItemList = (list: StoryItem[]) => {
  let map = new Map();
  let newList = []
  list.forEach((item) => {
    if (!item.subItems){
      item.subItems = [];

    }
    if (item.isRoot === CommonConstant.STORY_ITEM_IS_ROOT) {
      map.set(item.itemId, item);
      newList.push(item)
    }

  });

  list.forEach((item) => {
    if (item.isRoot !== CommonConstant.STORY_ITEM_IS_ROOT){
      map.get(item.masterItem)?.subItems?.push(item);
    }
  })
  return newList;
}
