const fs = require('fs').promises;
const {localizate} = require("./localization");

function sleep(ms) {
  return new Promise(resolve => setTimeout(resolve, ms));
}

async function loadPly(io) {
  const filename = './output/6/reconstruction_sequential/colorized.ply';
  const data = await fs.readFile(filename);
  const lines = data.toString().split('\n');
  const points = [];
  for (let i = 0; i < lines.length; i++) {
    const line = lines[i];
    const parts = line.split(" ");
    if(parts.length !== 6){
      continue;
    }
    const factor = 1;
    const x = parseFloat(parts[0]) * factor;
    const y = parseFloat(parts[1]) * factor;
    const z = parseFloat(parts[2]) * factor;
    const conf = parseFloat(1);
    points.push(x, y, z, conf);
    // console.log('lines', line);
  }
  const res = {pointcloud: points, hashCode: "9123923948"};
  await sleep(10000);
  io.emit("cam_pointcloud_web", res);
  console.log('done');
}

async function localizateOriginal(io){
  const data = {};
  console.log('start test');
  const dir = './input/6_renamed/';
  // const filename = './input/6/' + data.name + ".jpeg";
  const files = await fs.readdir(dir);
  files.sort((obj1, obj2) => {
    return obj1.localeCompare(obj2);
  });
  await loadPly(io);
  for (let i = 0; i < files.length; i++) {
    data.name = files[i].slice(0, files[i].length-5);
    const filename = dir + data.name + ".jpeg";
    const out = await localizate (filename, data.name + ".jpeg");
    const res = {...out, hashCode: "filecamera"};
    // console.log('res', res);
    // const out = localizate(commandQ);
    io.emit("cam_pos_web", res);
  }
}

module.exports = {localizateOriginal};