// Generated by CoffeeScript 1.3.1

/*
Copyright 2012 Mike Wakerly <opensource@hoho.com>

This file is part of the Pykeg package of the Kegbot project.
For more information on Pykeg or Kegbot, see http://kegbot.org/

Pykeg is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 2 of the License, or
(at your option) any later version.

Pykeg is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with Pykeg.  If not, see <http://www.gnu.org/licenses/>.
*/


(function() {
  var DrinkingSession, DrinkingSessionList, KegwebAppModel, POLL_INTERVAL_ACTIVE_SESSION, POLL_INTERVAL_NO_SESSION, PageSettings, PageSettingsView, SystemEvent, SystemEventList, SystemEventListView, SystemEventView,
    __indexOf = [].indexOf || function(item) { for (var i = 0, l = this.length; i < l; i++) { if (i in this && this[i] === item) return i; } return -1; };

  POLL_INTERVAL_ACTIVE_SESSION = 5 * 1000;

  POLL_INTERVAL_NO_SESSION = 60 * 1000;

  SystemEvent = Backbone.Model.extend({
    initialize: function(spec) {
      var eventImage, kind, title, username;
      kind = spec.kind;
      switch (kind) {
        case "drink_poured":
          title = "poured a drink";
          break;
        case "session_joined":
          title = "started drinking";
          break;
        case "session_started":
          title = "started a new session";
          break;
        default:
          title = "unknown event";
      }
      if (spec.user_id) {
        username = spec.user_id;
      } else {
        username = window.app.pageSettings.get("guestName");
      }
      this.id = spec.id;
      this.cid = this.id;
      eventImage = null;
      if (spec.image) {
        eventImage = spec.image.thumbnail_url;
      } else if (!spec.user) {
        eventImage = window.app.pageSettings.get("guestImageUrl");
      }
      this.set({
        kind: kind,
        htmlId: "systemevent_" + this.cid,
        eventTitle: title,
        eventUser: username,
        eventImage: eventImage
      });
      this.set(spec);
      return this;
    }
  });

  SystemEventView = Backbone.View.extend({
    render: function() {
      var el, kind, tmpl;
      kind = this.model.get("kind");
      switch (kind) {
        case "keg_tapped":
          tmpl = ich.systemevent_keg_started;
          break;
        case "keg_ended":
          tmpl = ich.systemevent_keg_ended;
          break;
        case "drink_poured":
          tmpl = ich.systemevent_drink_poured;
          break;
        case "session_started":
        case "session_joined":
          tmpl = ich.systemevent;
      }
      if (tmpl != null) {
        this.setElement(tmpl(this.model.toJSON()));
      }
      this.$("abbr.timeago").timeago();
      this.$("span.hmeasure").autounits({
        metric: window.app.pageSettings.get('metric')
      });
      el = this.$el;
      el.show();
      return this;
    }
  });

  SystemEventList = Backbone.Collection.extend({
    model: SystemEvent,
    initialize: function() {
      this.lastEventId = -1;
      this.on("add", function(event) {
        var ds, eventId, kind;
        kind = event.get("kind");
        eventId = parseInt(event.id);
        console.log("Event added: id=" + eventId + " kind=" + kind);
        if (eventId >= this.lastEventId) {
          this.lastEventId = eventId;
        }
        if (kind === "session_started") {
          ds = new DrinkingSession(event.get("session"));
          if (!app.drinkingSessions.get(ds.id)) {
            app.drinkingSessions.add(ds);
            ds.fetch({
              success: function(session) {
                console.log("New session " + session.id + " loaded.");
                return app.drinkingSessions.add(session);
              }
            });
          }
        }
      }, this);
      return this;
    },
    url: function() {
      if (this.length === 0) {
        return window.app.getApiBase() + "events/";
      } else {
        return window.app.getApiBase() + "events/?since=" + this.last().id;
      }
    },
    parse: function(response) {
      return response.objects;
    },
    comparator: function(e) {
      return e.id;
    }
  });

  SystemEventListView = Backbone.View.extend({
    el: $("#kb-system-events"),
    initialize: function(options) {
      this.collection.bind("add", function(model) {
        var eventView;
        this.setElement($("#kb-system-events"));
        eventView = new SystemEventView({
          model: model
        });
        $(this.el).prepend(eventView.render().el);
      }, this);
      return this;
    },
    render: function() {
      console.log("Event list: render!");
      return this;
    }
  });

  DrinkingSession = Backbone.Model.extend({
    urlRoot: function() {
      return window.app.getApiBase() + "sessions/";
    },
    initialize: function(spec) {
      this.id = spec.id;
      this.set(spec);
      return this;
    },
    parse: function(response) {
      return response.object;
    }
  });

  DrinkingSessionList = Backbone.Collection.extend({
    model: DrinkingSession,
    url: function() {
      return window.app.getApiBase() + "sessions/";
    },
    initialize: function() {
      this.on("add", function(session) {
        return console.log("Session added: " + session.get("id"));
      });
      return this;
    },
    comparator: function(session) {
      return session.get("id");
    },
    parse: function(response) {
      if (__indexOf.call(response, "objects") >= 0) {
        return response.objects;
      } else {
        return [];
      }
    }
  });

  PageSettings = Backbone.Model.extend({
    initialize: function(spec) {
      this.set({
        metric: false,
        guestName: "guest",
        guestImageUrl: null
      });
      return this.on("change:metric", function(model) {
        var useMetric;
        useMetric = this.get("metric");
        return $("span.hmeasure").autounits({
          metric: useMetric
        });
      }, this);
    },
    setMetric: function(useMetric) {
      if (useMetric == null) {
        useMetric = true;
      }
      return this.set({
        metric: useMetric
      });
    },
    toggleMetric: function() {
      return this.set({
        metric: !this.get("metric")
      });
    },
    setGuestInfo: function(name, imageUrl) {
      return this.set({
        guestName: name,
        guestImageUrl: imageUrl
      });
    }
  });

  PageSettingsView = Backbone.View.extend({
    initialize: function(options) {
      this.model.on("change:metric", function(model) {
        console.log("PageSettingsView: Settings changed");
        return this.render();
      }, this);
      return this;
    },
    render: function() {
      this.setElement($("#page-settings"));
      if (this.model.get("metric")) {
        return this.$el.html("<small>(current: metric)</small>");
      } else {
        return this.$el.html("<small>(current: imperial)</small>");
      }
    }
  });

  KegwebAppModel = Backbone.Model.extend({
    initialize: function(options) {
      this.systemEvents = new SystemEventList;
      this.drinkingSessions = new DrinkingSessionList;
      this.eventListView = new SystemEventListView({
        collection: this.systemEvents
      });
      this.pageSettings = new PageSettings;
      this.pageSettingsView = new PageSettingsView({
        model: this.pageSettings
      });
      this.set({
        "pageSettings": this.pageSettings
      });
      this.set({
        "apiBase": "/api/"
      });
      console.log("Kegbot app initialized!");
      return this;
    },
    setApiBase: function(url) {
      console.log("Api base URL set to " + url);
      return this.set({
        "apiBase": url
      });
    },
    getApiBase: function() {
      return this.get("apiBase");
    },
    getPageSettings: function() {
      return this.get("pageSettings");
    },
    refresh: function() {
      var have_active_session, timeout, update_fn;
      this.systemEvents.fetch({
        add: true
      });
      have_active_session = false;
      this.drinkingSessions.each(function(session) {
        if (session.get('is_active')) {
          have_active_session = true;
          return session.fetch();
        }
      });
      update_fn = _.bind(this.refresh, this);
      timeout = have_active_session ? POLL_INTERVAL_ACTIVE_SESSION : POLL_INTERVAL_NO_SESSION;
      return setTimeout(update_fn, timeout);
    }
  });

  window.app = new KegwebAppModel;

}).call(this);
