package com.wmyun.module.infra.service.file;

import cn.hutool.core.io.FileUtil;
import com.wmyun.farmwork.word.core.BookmarkExec;
import com.wmyun.farmwork.word.core.BookmarkQuery;
import com.wmyun.farmwork.word.core.model.BookmarkQueryDataModel;
import com.wmyun.farmwork.word.core.model.BookmarkReplaceDataModel;
import com.wmyun.module.infra.dal.dataobject.file.FileDO;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.File;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @Description: TODO
 * @Date: 2025/3/3 9:38
 * @Created: by ZZSLL
 */

@Service
public class WordBookmarkServiceImpl implements WordBookmarkService {

    @Autowired
    private FileService fileService;

    @Autowired
    private FilePreviewService previewService;

    @SneakyThrows
    @Override
    public Set<String> queryAllBookmarks(String fileId) {
        FileDO fileDO = previewService.queryFileInfoByFileId(fileId);
        return BookmarkQuery.queryAll(fileService.getFileContent(fileDO.getConfigId(), fileDO.getPath())).stream().map(BookmarkQueryDataModel::getName).collect(Collectors.toSet());
    }

    @SneakyThrows
    @Override
    public Long replaceBookmarkWithContent(String fileId, List<BookmarkReplaceDataModel> data) {
        FileDO fileDO = previewService.queryFileInfoByFileId(fileId);
        byte[] content = fileService.getFileContent(fileDO.getConfigId(), fileDO.getPath());
        File file = FileUtil.newFile(BookmarkExec.tmpDir + fileDO.getName());
        FileUtil.writeBytes(content, file);
        File outputFile = BookmarkExec.replace(data, content, file);
        return fileService.createFileDO(outputFile.getName(), outputFile.getAbsolutePath(), FileUtil.readBytes(outputFile)).getId();
    }
}
