import { Component, OnInit } from '@angular/core';
import { ActivatedRoute } from "@angular/router";
import { Server } from "../../../../server";
import { ServerModel } from "../../../../models/atlasData/server.model";
import { IslandDataModel } from "../../../../../data/models/island-data.model";
import { IslandInstanceModel } from "../../../../models/atlasData/island-instance.model";
import { ServerSublevelModel } from "../../../../models/atlasData/serverSublevel.model";

@Component({
  selector: 'app-server',
  templateUrl: './server.component.html'
})
export class ServerComponent implements OnInit {
  private cell: ServerModel;
  private templateOptions: string[];
  private islandOptions: object = {};

  constructor(private server: Server, private route: ActivatedRoute) {
  }

  ngOnInit() {
    let index = this.route.snapshot.paramMap.get('index');
    this.cell = this.server.serverGrid.servers[index];
    this.templateOptions = this.server.serverGrid.serverTemplates.map(i => i.name);
    Object.values(this.server.islands).forEach((i: IslandDataModel) => this.islandOptions[i.name] = i.customDisplayName());
  }

  private changeIslandModel(index: number, name: string) {
    let oldIsland = this.cell.islandInstances[index];
    const newIslandData = this.server.islands[name];
    const oldIslandData = this.server.islands[oldIsland.name];

    let newIsland = IslandInstanceModel.fromIslandData(newIslandData);

    // keep X, Y and Rotation the same
    newIsland.worldX = oldIsland.worldX;
    newIsland.worldY = oldIsland.worldY;
    newIsland.rotation = oldIsland.rotation;

    // Remove old Sublevels
    oldIslandData.sublevelNames.forEach(i => {
      const j = this.cell.sublevels.findIndex(sublevel => sublevel.name === i);
      if (j > -1) {
        this.cell.sublevels.splice(j, 1);
      }
    });

    // Get new unique ID
    newIsland.id = this.server.serverGrid.getNextId();

    // Add new Sublevels
    newIslandData.sublevelNames.forEach(i => {
      let newSublevel = new ServerSublevelModel();
      newSublevel.name = i;
      newSublevel.setupFromIsland(newIsland, newIslandData, this.cell, this.server.serverGrid);
      this.cell.sublevels.push(newSublevel);
    });

    this.cell.islandInstances[index] = newIsland;

    this.updateExtraSublevels();
  }

  private updateExtraSublevels() {
    // Extra Sublevels can be identical across multiple islands,
    // so need to merge any changes. Easiest to just merge through
    // all of the available islands instead.
    this.cell.totalExtraSublevels = [];
    this.cell.islandInstances.forEach(i => {
      const islandData = this.server.islands[i.name];
      islandData.extraSublevels.forEach(j => {
        if (this.cell.totalExtraSublevels.indexOf(j) === -1) {
          this.cell.totalExtraSublevels.push(j);
        }
      });
    });
  }
}
