const fs = require('fs');
const path = require('path');

// Constants
const WORLD_LOAD_TOKEN = ";";
const TILE_FLAG_DYNAMIC = 1;

// Method.
const saveWorld = (world) => {
  const pathWorld = path.join(__dirname, '..', '..', 'assets', world.name);
  if(!fs.existsSync(pathWorld)) fs.mkdirSync(pathWorld);

  // World string buffer (file data).
  let strBuffer = "";

  // Header
  strBuffer += [
    world.version,
    world.tileset,
    ""// Seal
  ].join(WORLD_LOAD_TOKEN);

  // Tilemap Definition
  let buffer = [];
  for(let i = 0; i < world.tilemap.length; i++) {
    let tileDef = world.tilemap[i];
    buffer.push(tileDef.verticeCount+'');
    buffer.push(tileDef.indiceCount+'');
    buffer.push(tileDef.flags+'');
  }
  strBuffer += buffer.join(WORLD_LOAD_TOKEN);
  
  fs.writeFileSync(path.join(pathWorld, 'world.txt'), strBuffer);
}

// Worlds.
const TILEMAP_WIDTH = 8;
const TILEMAP_HEIGHT = 298;

let world = {
  version: '1.00',
  tileset: 'tileset.png',
  name: 'testworld',
  tilemap: [ ]
};

for(let i = 0; i < TILEMAP_WIDTH * TILEMAP_HEIGHT; i++) {
  world.tilemap[i] = {
    indiceCount: 6,
    verticeCount: 4,
    flags: 0
  };
}

console.log('bruh', world);
saveWorld(world);