import { Injectable } from '@angular/core';
import { ServerGridModel } from "./models/serverGrid.model";
import * as islandData from '../data/islands.json';
import { IslandDataModel } from "../data/models/island-data.model";

@Injectable()
export class Server {
  private rawData: string = "";
  private jsonData: object = {};
  public serverGrid: ServerGridModel = new ServerGridModel();
  public islands;

  constructor() {
    this.islands = (islandData as any).default;
    Object.keys(this.islands).forEach(i => {
      this.islands[i] = new IslandDataModel().deserialize(this.islands[i])
    });
  }

  public load(raw) {
    this.rawData = raw;
    try {
      this.jsonData = JSON.parse(this.rawData);
      this.serverGrid = new ServerGridModel().deserialize(this.jsonData);
    } catch (e) {
      console.log(e);
    }
  }

  public save() {
    this.rawData = JSON.stringify(this.serverGrid, null, 2);
    return this.rawData;
  }
}