"use strict";

var ObjectWithListeners = require('./ObjectWithListeners');

/**
 * Class Configuration is responsible for load a configuration from a text file
 * conected to current project (in one project it is possible to show many
 * maps).
 */
function Configuration(data) {
  // call super constructor
  ObjectWithListeners.call(this);

  // set default values
  this.TILE_SIZE = 256;
  this.PICTURE_SIZE = 256;
  this.MAX_ZOOM = 4;
  this.MIN_ZOOM = 2;
  this.IMG_DIR = "images/";
  this.MAP_NAME = "unknown map";
  this.MAPS = [];
  this.SUBMODELS = [];

  this.speciesAddr = "species";
  this.miriamAddr = "miriam";
  this.feedbackAddr = "feedback";

  this.registerListenerType("onreload");

  if (data !== undefined) {
    this.loadFromModelView(data);
  }
}

// this class inherits from ObjectWithListeners class where generic methods for
// listeners are set
Configuration.prototype = Object.create(ObjectWithListeners.prototype);
Configuration.prototype.constructor = Configuration;

/**
 * Updates configuration data from object passed from server side.
 * 
 * @param modelView
 *          object retrieved from server side
 */
Configuration.prototype.loadFromModelView = function(modelView) {
  if (typeof modelView === "string") {
    // replace is due to some strange problem with serialization
    modelView = JSON.parse(modelView.replace(/\n/g, " "));
  }
  this.setId(parseInt(modelView.idObject));
  this.TILE_SIZE = modelView.tileSize;
  this.PICTURE_SIZE = modelView.pictureSize;
  this.MAX_ZOOM = modelView.maxZoom;
  this.MIN_ZOOM = modelView.minZoom;
  this.MAP_NAME = modelView.version;
  this.setCenter(modelView.centerLatLng);

  this.addLayouts(modelView.layouts);
  this.addLayouts(modelView.customLayouts);

  this.SUBMODELS = [];
  if (modelView.submodels !== undefined) {
    for (var i = 0; i < modelView.submodels.length; i++) {
      var conf = new Configuration();
      conf.loadFromModelView(modelView.submodels[i]);
      this.SUBMODELS.push(conf);
    }
  }

  this.TOP_OVERVIEW_IMAGE = modelView.topOverviewImage;
  this.OVERVIEW_IMAGES = modelView.overviewImageViews;

  this.topLeftLatLng = modelView.topLeftLatLng;
  this.bottomRightLatLng = modelView.bottomRightLatLng;
  this.fitMapBounds = modelView.fitMapBounds;

  this.callListeners("onreload");
};

Configuration.prototype.getId = function() {
  return this.ID_MODEL;
};

Configuration.prototype.setId = function(id) {
  this.ID_MODEL = id;
};

Configuration.prototype.setCenter = function(center) {
  if (center !== undefined) {
    this.CENTER_LAT = center.lat;
    this.CENTER_LNG = center.lng;
  }
};

Configuration.prototype.addLayout = function(layout) {
  this.MAPS.push(layout);
};

Configuration.prototype.addLayouts = function(layouts) {
  if (layouts !== undefined) {
    this.MAPS = this.MAPS.concat(layouts);
  }
};

module.exports = Configuration;