const { ipcRenderer } = window.require("electron");

// ========== 原素材下载 API（原有保留） ==========

/**
 * 提交下载任务
 * @param {Object} params { urls, targetPath, batchArrangeNum }
 * @returns {Promise<Object>}
 */
export function submitDownload(params) {
  return new Promise(resolve => {
    ipcRenderer.once("download:submit-reply", (_, res) => resolve(res));
    ipcRenderer.send("download:submit", params);
  });
}

/**
 * 获取当前下载状态
 * @returns {Promise<Object>}
 */
export function getDownloadStatus() {
  return new Promise(resolve => {
    ipcRenderer.once("download:getStatus-reply", (_, res) => resolve(res));
    ipcRenderer.send("download:getStatus");
  });
}

/**
 * 监听下载状态变更
 * @param {Function} callback
 * @returns {Function} 取消监听函数
 */
export function onDownloadStatusChange(callback) {
  const handler = (_, data) => callback(data);
  ipcRenderer.on("download:status", handler);
  return () => ipcRenderer.removeListener("download:status", handler);
}
// ========== 新增：手动排版下载 API ==========

/**
 * 提交手动排版下载任务
 * @param {Object} params { urlStr: 逗号分隔URL字符串, targetPath: 保存目录 }
 * @returns {Promise<Object>}
 */
export function submitTypesettingDownload(params) {
  return new Promise(resolve => {
    ipcRenderer.once("download-typesetting:submit-reply", (_, res) =>
      resolve(res)
    );
    ipcRenderer.send("download-typesetting:submit", params);
  });
}

/**
 * 查询手动排版下载状态
 * @returns {Promise<Object>}
 */
export function getTypesettingDownloadStatus() {
  return new Promise(resolve => {
    ipcRenderer.once("download-typesetting:getStatus-reply", (_, res) =>
      resolve(res)
    );
    ipcRenderer.send("download-typesetting:getStatus");
  });
}

/**
 * 监听手动排版下载状态变更
 * @param {Function} callback
 * @returns {Function} 取消监听函数
 */
export function onTypesettingStatusChange(callback) {
  const handler = (_, data) => callback(data);
  ipcRenderer.on("download-typesetting:status", handler);
  return () =>
    ipcRenderer.removeListener("download-typesetting:status", handler);
}
