'use strict';

const rethinkDB = require('rethinkdb');

const log = require('./../server/log');

export class Location {
  constructor(conn, locationSize, locationId, dungeonBP) {
    this.conn = conn;
    this.locationSize = locationSize;
    this.locationId = locationId;
    this.dungeonBP = dungeonBP;

    this.locationMap = [];
    for (let i = 0; i < locationSize; i++) this.locationMap.push([]);
  }

  createTable() {
    rethinkDB
      .tableCreate(this.locationId)
      .run(this.conn, (err) => {
        if (err) {
          log.error(`Table for ${this.locationId} not created`);
          throw err;
        }

        log.info(`Table for ${this.locationId} created`);
        this.writeNewLocationMap();
      });
  }

  writeNewLocationMap() {
    let buffer = [];

    for (let y = 0; y < this.locationMap.length; y++) {
      let mapRow = this.locationMap[y];

      for (let x = 0; x < mapRow.length; x++) {
        let elem = {};
        elem['x'] = x;
        elem['y'] = y;
        elem['type'] = mapRow[x];
        buffer.push(elem);
      }
    }

    rethinkDB
      .table(this.locationId)
      .insert(buffer)
      .run(this.conn, (err, res) => {
        if (err) {
          log.error(`Data for ${this.locationId} not inserted`);
          throw err;
        }

        log.info(`Location map done. We inserted ${res['inserted']} elements to ${this.locationId}`);
        log.info(`Let's create the index for ${this.locationId}!`);

        rethinkDB
          .table(this.locationId)
          .indexCreate('coord', [rethinkDB.row('x'), rethinkDB.row('y')])
          .run(this.conn, (err) => {
            if (err) {
              log.error(`Index for ${this.locationId} not created`);
              throw err;
            }

            rethinkDB
              .table(this.locationId)
              .indexWait('coord')
              .run(this.conn, (err) => {
                if (err) throw err;

                log.info(`Index for ${this.locationId} created!`);
              });
          });
      });
  }
}

@@ -728,16 +728,702 @@
 );%0A  %7D%0A%0A
+  createDungeonTunnel (type, level) %7B%0A    if (this.dungeonBP) %7B%0A      if (level === -1) %7B%0A        // add entrance from surface to dungeon%0A        const x = this.dungeonBP.entrances%5B0%5D%5B0%5D;%0A        const y = this.dungeonBP.entrances%5B0%5D%5B1%5D;%0A        this.locationMap%5By%5D%5Bx%5D = 2.1;%0A      %7D else %7B%0A        if (this.dungeonBP.entrances.length %3E level) %7B%0A          const x = this.dungeonBP.entrances%5Blevel%5D%5B0%5D;%0A          const y = this.dungeonBP.entrances%5Blevel%5D%5B1%5D;%0A          this.locationMap%5By%5D%5Bx%5D = type;%0A        %7D%0A      %7D%0A    %7D%0A  %7D%0A%0A  createDungeonEntrance (level) %7B%0A    this.createDungeonTunnel(2.1, level);%0A  %7D%0A%0A  createDungeonExit (level) %7B%0A    this.createDungeonTunnel(2.2, level);%0A  %7D%0A%0A
   writeN

Add methods createDungeonTunnel, createDungeonEntrance and createDungeonExit