include("parseMqoObject.js");
var controlpng = Resources.id("mtr:m3_i/control/e233_control.png");
var partpng = Resources.id("mtr:m3_i/control/parts_233.png");
var partpng2 = Resources.id("mtr:m3_i/control/e233_part2.png");
//var controlmodel = Resources.id("mtr:m3_i/m3_19_i_cab_forwards.mqo");
const mqoText = Resources.read(Resources.id("mtr:m3_i/m3_19_i_cab_forwards.mqo"));
const mqoTextStr = mqoText.asString()

const jsData = parseMqoObject(mqoTextStr);
//const mqoToJsFile = convertMqoObjectsToJs(jsData);
const mqoData = {
  object_panel:{
    vertex: [
      [115.9987, 90, 1054],
      [-2.0013008, 90, 1054],
      [116, 118.99998, 1053.996],
      [-2, 118.99998, 1053.996]
    ],
    face: {
      vertexCount: 4,
      V: [2, 0, 1, 3],
      uv: [
        0.36718, 0.87695,
        0.36718, 0.90527,
        0.25195, 0.90527,
        0.25195, 0.87695
      ]
    }
  }
};
const mqoData2 = {
 object_panel_2_2:{
  vertex: [
    [59.397247, 93.451004, 1054.5],
    [28.599815, 93.451004, 1054.5],
    [59.398926, 116.54897, 1054.496],
    [28.601479, 116.54897, 1054.496]
  ],
  face: {
    vertexCount: 4,
    V: [2, 0, 1, 3],
    uv: [
      0.403125, 0.744987,
      0.403125, 0.746094,
      0.401367, 0.746094,
      0.401367, 0.744987
    ]
  }
 }
};
const mqoDataControl = {
   object_panel_1_1:{
  vertex: [
    [106.9987, 98, 1054],
    [79.998703, 98, 1054],
    [107, 114.99998, 1053.996],
    [80, 114.99998, 1053.996]
  ],
  face: {
    vertexCount: 4,
    V: [2, 0, 1, 3],
    uv: [
      0.26416, 0.000488281,
      0.26416, 0.166504,
      0.000488281, 0.166504,
      0.000488281, 0.000488281
    ]
  }
 },
 object_panel_2_1:{
  vertex: [
    [55.998703, 96, 1054],
    [31.998699, 96, 1054],
    [56, 113.99998, 1053.996],
    [32, 113.99998, 1053.996]
  ],
  face: {
    vertexCount: 4,
    V: [2, 0, 1, 3],
    uv: [
      0.117481, 0.166992,
      0.117481, 0.254883,
      0.000488281, 0.254883,
      0.000488281, 0.166992
    ]
  }
 }
};


const { rawModelMap: rawModelMapPanel, codeStringMap: codeStringMapPanel } = mqoDataToJs(mqoData, partpng);

const { rawModelMap: rawModelMapPanel2, codeStringMap: codeStringMapPanel2 } = mqoDataToJs(mqoData2, partpng);
const { rawModelMap: rawModelMapControl, codeStringMap: codeStringMapControl } = mqoDataToJs(mqoDataControl, controlpng);

// 取得 RawModel (builders returned by mqoDataToJs)
const mqoModelPanel = rawModelMapPanel.get("object_panel");

const mqoModelPanel_1_1 = rawModelMapControl.get("object_panel_1_1");
const mqoModelPanel_2_1 = rawModelMapControl.get("object_panel_2_1");
const mqoModelPanel_2_2 = rawModelMapPanel2.get("object_panel_2_2");

// Build and upload models
const mqoModelArray = [
  mqoModelPanel,
  mqoModelPanel_1_1,
  mqoModelPanel_2_1,
  mqoModelPanel_2_2
];

const modelArray = [];
const rawModelArray = [];

for (let index = 0; index < mqoModelArray.length; index++) {
  let builder = mqoModelArray[index];
  rawModelArray[index] = new RawModel();
  rawModelArray[index].append(builder.getMesh());   // 每個 builder 的 mesh
  rawModelArray[index].triangulate();
  rawModelArray[index].generateNormals();

  // 上傳並存到陣列
  let uploadedModel = ModelManager.upload(rawModelArray[index]);
  modelArray.push(uploadedModel);
}

function create(ctx, state, vehicle) {
console.log("keys:", Object.keys(jsData));
console.log("panel:", jsData["panel"]);
}

function render(ctx, state, vehicle) {
    
      for(let carIndex of ctx.getMyCars()) {
          let renderManager = ctx.getCarRenderManager(carIndex);
          modelArray.forEach(element => {
            renderManager.drawModel(element, null); // Draw the model out
          });
      }
    
}

function dispose(ctx, state, vehicle) {

};

function mqoToJs(mqoData, textureName) {
  const rawMeshBuilder = new RawMeshBuilder(
    mqoData.face.vertexCount,
    "exterior",
    textureName
  );

  // face.V 是頂點索引陣列，例如 [3,1,0,2]
  mqoData.face.V.forEach((vertexIndex, i) => {
    const v = mqoData.vertex[vertexIndex];
    const u = mqoData.face.uv[i * 2];
    const vCoord = mqoData.face.uv[i * 2 + 1];

    rawMeshBuilder
      .vertex(v[0] / 100, v[1] / 100, v[2] / 100)
      .normal(0, 0, 0)
      .uv(u, vCoord)
      .endVertex();
  });

  return rawMeshBuilder;
}

function mqoDataToJs(mqoData, textureName) {
  const rawModelMap = new Map();
  const codeStringMap = new Map();

  Object.entries(mqoData).forEach(([objectName, obj]) => {
    const builder = new RawMeshBuilder(obj.face.vertexCount, "exterior", textureName);

    // 先複製一份 uv
    const uv = [...obj.face.uv];

    // 對調前兩個 U 與後兩個 U
    // uv 陣列結構: [u0,v0, u1,v1, u2,v2, u3,v3]
    const tempU0 = uv[0], tempU1 = uv[2];
    uv[0] = uv[4]; // u0 ← u2
    uv[2] = uv[6]; // u1 ← u3
    uv[4] = tempU0; // u2 ← 原本 u0
    uv[6] = tempU1; // u3 ← 原本 u1

    obj.face.V.forEach((vertexIndex, i) => {
      const v = obj.vertex[vertexIndex];
      const u = uv[i * 2];
      const vCoord = uv[i * 2 + 1];

      builder
        .vertex(v[0] / 100, v[1] / 100, v[2] / 100)
        .normal(0, 0, 0)
        .uv(u, vCoord)
        .endVertex();
    });

    rawModelMap.set(objectName, builder);

    // 同時生成 JS 代碼字串
    let code = `const ${objectName} = new RawMeshBuilder(${obj.face.vertexCount}, "exterior", "${textureName}");\n`;
    obj.face.V.forEach((vertexIndex, i) => {
      const v = obj.vertex[vertexIndex];
      const u = uv[i * 2];
      const vCoord = uv[i * 2 + 1];

      code += `${objectName}\n`
        + `  .vertex(${v[0] / 100}, ${v[1] / 100}, ${v[2] / 100})\n`
        + `  .normal(0, 0, 0)\n`
        + `  .uv(${u}, ${vCoord})\n`
        + `  .endVertex();\n`;
    });

    codeStringMap.set(objectName, code);
  });

  return { rawModelMap, codeStringMap };
}



