var BgGen     = require('../bg-gen');
var Immutable = require('immutable');

var Reflux = require('reflux');
var NoteActions = require('../actions/NoteActions');

var _notesByName = Immutable.OrderedMap();

var localNotes = localStorage && localStorage['notes'];
if (localNotes) {
  _notesByName = _notesByName.mergeDeep(JSON.parse(localNotes));
}

function deserializeNote(noteName, note) {
  note.name = noteName;
  note.createdAt = new Date(note.createdAt);
  note.localHidden = note.hidden;

  var noteInLocalStorage = _notesByName.get(note.name);
  var style = (noteInLocalStorage && noteInLocalStorage.get('style'))
    || Immutable.Map((new BgGen()).toStyle());
  note.style = style;

  return Immutable.Map(note);
}

var NoteStore = Reflux.createStore({
  listenables: NoteActions,

  getAll: function() {
    return _notesByName;
  },

  clearAll: function() {
    _notesByName = Immutable.OrderedMap();
  },

  onNoteAdded: function(noteName, note) {
    note = deserializeNote(noteName, note);
    _notesByName = _notesByName.set(note.get('name'), note);
    this.triggerAsync();
  },

  onNoteRemoved: function(noteName) {
    _notesByName = _notesByName.remove(noteName);
    this.triggerAsync();
  },

  onNoteChanged: function(noteName, note) {
    var newNote = _notesByName.get(noteName).merge(note);
    newNote = newNote.set('localHidden', note.hidden);
    _notesByName = _notesByName.set(noteName, newNote);
    this.triggerAsync();
  },

  onToggleLocalHidden: function(note) {
    var newNote = note.set('localHidden', !note.get('localHidden'));
    _notesByName = _notesByName.set(note.get('name'), newNote);
    this.triggerAsync();
  }
});

module.exports = NoteStore;

@@ -249,17 +249,60 @@
 rage
-%5B'
+.
 notes
-'%5D
+;%0Avar coldNotesByName = Immutable.OrderedMap()
 ;%0Aif
@@ -319,18 +319,21 @@
 es) %7B%0A  
-_n
+coldN
 otesByNa
@@ -329,34 +329,37 @@
 ldNotesByName = 
-_n
+coldN
 otesByName.merge
@@ -554,25 +554,25 @@
 teIn
-LocalStorage = _n
+ColdNotes = coldN
 otes
@@ -619,42 +619,36 @@
 teIn
-LocalStorage && noteInLocalStorage
+ColdNotes && noteInColdNotes
 .get
@@ -661,15 +661,15 @@
 e'))
+ %7C%7C
 %0A   
- %7C%7C
  Imm
@@ -869,24 +869,68 @@
 _notesByName
+.size !== 0 ? _notesByName : coldNotesByName
 ;%0A  %7D,%0A%0A  cl

Fix deleted notes weren't being deleted from local copy