var Whisper = Whisper || {};

(function () {
  'use strict';

  var Thread = Backbone.Model.extend({
    defaults: function() {
      return {
        image: '/images/default.png',
        unreadCount: 0,
        timestamp: new Date().getTime()
      };
    },

    validate: function(attributes, options) {
      var required = ['id', 'type', 'timestamp', 'image', 'name'];
      var missing = _.filter(required, function(attr) { return !attributes[attr]; });
      if (missing.length) { return "Thread must have " + missing; }
    },

    sendMessage: function(message) {
      var m = Whisper.Messages.addOutgoingMessage(message, this);
      if (this.get('type') == 'private')
        var promise = textsecure.messaging.sendMessageToNumber(this.get('id'), message, []);
      else
        var promise = textsecure.messaging.sendMessageToGroup(this.get('id'), message, []);
      promise.then(
        function(result) {
          console.log(result);
        }
      ).catch(
        function(error) {
          console.log(error);
        }
      );
    },

    messages: function() {
      var messages = new Whisper.MessageCollection([], {threadId: this.id});
      messages.fetch();
      return messages;
    },
  });

  Whisper.Threads = new (Backbone.Collection.extend({
    localStorage: new Backbone.LocalStorage("Threads"),
    model: Thread,
    comparator: 'timestamp',
    findOrCreate: function(attributes) {
      var thread = Whisper.Threads.add(attributes, {merge: true});
      thread.save();
      return thread;
    },

    findOrCreateForRecipient: function(recipient) {
      var attributes = {};
	  attributes = {
	    id        : recipient,
	    name      : recipient,
	    type      : 'private',
	  };
      return this.findOrCreate(attributes);
    },

    findOrCreateForIncomingMessage: function(decrypted) {
      var attributes = {};
      if (decrypted.message.group) {
        attributes = {
          id         : decrypted.message.group.id,
          name       : decrypted.message.group.name,
          type       : 'group',
        };
      } else {
        attributes = {
          id         : decrypted.pushMessage.source,
          name       : decrypted.pushMessage.source,
          type       : 'private'
        };
      }
      return this.findOrCreate(attributes);
    }
  }))();
})();

@@ -1,12 +1,44 @@
+/* vim: ts=2:sw=2:expandtab: */%0A
 var Whisper 
@@ -705,16 +705,18 @@
 rivate')
+ %7B
 %0A       
@@ -797,24 +797,32 @@
 ssage, %5B%5D);%0A
+      %7D%0A
       else%0A 
@@ -819,16 +819,18 @@
     else
+ %7B
 %0A       
@@ -910,24 +910,32 @@
 ssage, %5B%5D);%0A
+      %7D%0A
       promis
@@ -1668,17 +1668,20 @@
 s = %7B%7D;%0A
-%09
+    
   attrib
@@ -1689,17 +1689,20 @@
 tes = %7B%0A
-%09
+    
     id  
@@ -1716,25 +1716,28 @@
  recipient,%0A
-%09
+    
     name    
@@ -1755,13 +1755,16 @@
 nt,%0A
-%09
+   
     
+ 
 type
@@ -1786,9 +1786,12 @@
 e',%0A
-%09
+    
   %7D;

Fix whitespace, lint