import useEventStore from '@/components/nova-sdk/store/useEventStore';
import { TaskArtifact } from '../types';
import { RefObject, useEffect } from 'react';
import { ImageEditorHandle } from '@/components/image-editor';

export const useImages = (imageEditorRef: RefObject<ImageEditorHandle | null>) => {
  const processEvents = useEventStore((store) => store.processEvents);
  // 提取事件流中的图片产物资源
  const images = processEvents.reduce((pre, cur) => {
    const renderProps = cur.renderProps || {};
    const imageAttachment = renderProps.imageAttachment;
    if (imageAttachment) {
      const taskArtifacts = imageAttachment.map((item: any) => {
        return {
          path: item.path,
          file_name: item.file_name,
          file_type:
            item.file_type || (item.file_name || '').split('.').pop() || '',
        };
      });
      pre.push(...taskArtifacts);
    }
    return pre;
  }, [] as TaskArtifact[]);

  // 响应式监听图片资源变化，并批量同步至编辑器
  useEffect(() => {
    if (images.length > 0) {
      imageEditorRef.current?.addArtifacts(images);
    }
  }, [images, imageEditorRef]);
}