(function() {
  function TileController() {
    this._server = 'https://ggj2017-progm.herokuapp.com';
    // this._server = 'http://localhost:8000';
    this._changes = [];
    this._serverData = null;
    this._interval = null;
  }

  TileController.prototype.screenshot = function() {
    var snap = SceneManager.snap();
    var urlData = snap._canvas.toDataURL('png');
    $.ajax({
      type: "POST",
      url: this._server + "/upload",
      data: {
         image: urlData
      }
    }).done(function(o) {
      console.log('saved');
      console.log(o);
    });
  }

  TileController.prototype.changes = function(id) {
    return this._changes.indexOf(id) !== -1;
  }

  TileController.prototype.data = function() {
    return this._data;
  }

  TileController.prototype.startSync = function() {
    if (this._interval) return;
    this._interval = setInterval(this.sync.bind(this), 200);
  }

  TileController.prototype.stopSync = function() {
    if (!this._interval) return;
    clearInterval(this._interval);
    this._interval = null;
  }

  TileController.prototype.sync = function() {
    var that = this;
    $.ajax({
      type: "GET",
      url: this._server + '/client/changes'
    }).done(function(data) {
      console.log(data);
      that._changes = data;
    })
  }

  TileController.prototype.reset = function() {
    this._changes = [];
    var that = this;
    $.ajax({
      type: "DELETE",
      url: this._server + '/client/changes'
    }).done(function(data) {
      that._changes = [];
    })
  }

  TileController.prototype.setServerData = function(partialData) {
    var that = this;
    $.ajax({
      type: "POST",
      contentType : 'application/json',
      url: this._server + '/server/partial_data',
      data: JSON.stringify(partialData),
    }).done(function(data) {
      that._serverData = data;
    })
  }

  TileController.prototype.resetServerData = function(newServerData) {
    var that = this;
    this._serverData = newServerData;
    $.ajax({
      type: "POST",
      contentType : 'application/json',
      url: this._server + '/server/data',
      data: JSON.stringify(this._serverData),
    }).done(function(data) {
      that._serverData = data;
    })
  }

  TileController.prototype.move = function(id, x, y) {
    $.ajax({
      type: "GET",
      contentType : 'application/json',
      url: this._server + '/client/set_moves?x=' + x + "&y=" + y + "&id=" + id,
    }).done(function(data) {
      console.log(data);
    })
  }

  window.$tileController = new TileController();
})();
