import fs from "node:fs";

function convertDatToObj(datFilename, objFilename) {
  const lines = fs.readFileSync(datFilename, "utf-8").split("\n");

  // 检查对称性标志
  const symmetryFlag = lines[0].split()[1] === "1";
  const vertices = [];
  const faces = [];

  // 开始转换为 .obj 格式
  const objFile = fs.createWriteStream(objFilename);

  // 写入顶点数据
  for (let i = 1; i < lines.length; i++) {
    // 跳过第一行
    if (lines[i].trim() === "0 0. 0. 0.") {
      // 节点表结束标志
      break;
    }
    const parts = lines[i].split();
    vertices.push([
      parseFloat(parts[1]),
      parseFloat(parts[2]),
      parseFloat(parts[3]),
    ]);
    objFile.write(`v ${parts[1]} ${parts[2]} ${parts[3]}\n`);
  }

  // 如果模型是对称的，添加镜像顶点
  if (symmetryFlag) {
    for (const v of vertices) {
      objFile.write(`v ${v[0]} ${-v[1]} ${v[2]}\n`);
    }
  }

  // 跳过中间的0行和连接表的标题行
  const connectionStartIndex = lines.indexOf("0 0. 0. 0.\n") + 2;

  // 写入面数据
  for (let i = connectionStartIndex; i < lines.length; i++) {
    if (lines[i].trim() === "0 0 0 0") {
      // 连接表结束标志
      break;
    }
    const parts = lines[i].split();
    faces.push([
      parseInt(parts[0]),
      parseInt(parts[1]),
      parseInt(parts[2]),
      parseInt(parts[3]),
    ]);
    objFile.write(`f ${parts[0]} ${parts[1]} ${parts[2]} ${parts[3]}\n`);
  }

  // 如果模型是对称的，添加镜像面
  if (symmetryFlag) {
    const offset = vertices.length;
    for (const f of faces) {
      // 注意：我们需要改变顶点的顺序来保持法线方向正确
      objFile.write(
        `f ${f[0] + offset} ${f[3] + offset} ${f[2] + offset} ${f[1] + offset}\n`,
      );
    }
  }

  objFile.end();
}

export { convertDatToObj };
