import { Component, OnInit } from '@angular/core';
import { Server } from "../../../server";
import { ServerGridModel } from "../../../models/serverGrid.model";
import { ServerModel } from "../../../models/atlasData/server.model";
import { Router } from "@angular/router";

@Component({
  selector: 'app-servers',
  templateUrl: './servers.component.html'
})
export class ServersComponent implements OnInit {
  private grid: ServerGridModel;

  private xArray: number[];
  private yArray: number[];

  private serverLookup: number[][] = [];
  private unknownServers: number[] = [];

  constructor(private server: Server, private router: Router) {
    this.grid = server.serverGrid;
    this.xArray = Array.from(Array(this.grid.totalGridsX).keys());
    this.yArray = Array.from(Array(this.grid.totalGridsY).keys());

    // Initialise the serverLookup with x at least
    this.xArray.forEach(i => this.serverLookup[i] = []);

    this.grid.servers.forEach((i, index) => {
      if (i.gridX < this.grid.totalGridsX && i.gridY < this.grid.totalGridsY) {
        if (this.serverLookup[i.gridX] === undefined)
          this.serverLookup[i.gridX] = [];
        this.serverLookup[i.gridX][i.gridY] = index;
      } else {
        this.unknownServers.push(index);
      }
    });
  }

  ngOnInit() {
  }

  private addNewServer(x: number, y: number) {
    let newServer = new ServerModel();
    newServer.gridX = x;
    newServer.gridY = y;
    const newLength = this.grid.servers.push(newServer);
    return this.router.navigate(['/config', 'server', newLength - 1]);
  }
}
