/**
 * Data model provider.
 *
 * @package appmaker
 * @author  Andrew Sliwinski <a@mozillafoundation.org>
 */

var MakeDrive = require('makedrive');
var watch = require('watchjs').watch;

/**
 * Constructor
 */
function Model () {
    var self = this;
    self._fs = MakeDrive.fs({manual: true});
    self._sync = self._fs.sync;
    self._sync.connect("ws://makedrive.alicoding.com");
    self._sync.on('connected', function() {
        console.log('Connected to MakeDrive');
    });
    self._sync.on('error', function(err) {
        console.error(err);
    });
    self._sync.on('completed', function() {
        console.log('Sync Completed');
    });
    self._sync.on('syncing', function() {
        console.log('Syncing');
    });
    // Internal
    self._ns = '/_model';
    self._ready = false;
    self._logger = function (prefix, msg) {
        if (typeof msg === 'undefined') {
            msg = prefix;
            prefix = 'Model';
        }

        if (msg) console.log('[' + prefix + '] ' + msg);
    };

    // Public
    self.history = {
        ftu: true,
        path: '/ftu'
    };
    self.locale = null;
    self.user = {
        name: null,
        location: null,
        avatar: null
    };
    self.apps = [
        {
            id: '000d1745-5d3c-4997-ac0c-15df68bbbecz',
            name: 'Sample App',
            icon: '/images/placeholder_puppy.png',
            author: {
                name: 'Andrew',
                location: 'Portland',
                avatar: '/images/avatar_puppy.png'
            },
            blocks: []
        }
    ];
}

/**
 * Restores the model from localforage.
 *
 * @param  {Function} callback
 *
 * @return {void}
 */
Model.prototype.restore = function (callback) {
    var self = this;
    self._fs.readFile(self._ns, function(err, item) {
        if (err && err.code === "ENOENT") {
            self.observe();
            return callback(null);
        }

        if (typeof item.history !== 'undefined') self.history = item.history;
        if (typeof item.user !== 'undefined') self.user = item.user;
        if (typeof item.apps !== 'undefined') self.apps = item.apps;
        if (typeof item.locale !== 'undefined') self.locale = item.locale;

        self.observe();
        self._logger('Data restored');

        callback(null);
    });
};

/**
 * Saves the current model state to localforage.
 *
 * @param  {Function} callback
 *
 * @return {void}
 */
Model.prototype.save = function (callback) {
    var self = this;
    callback = callback || function (){};

    var item = {
        history: self.history,
        user: self.user,
        apps: self.apps,
        locale: self.locale,
    };
    putItem = JSON.stringify(item);
    self._fs.writeFile(self._ns, putItem, function (item) {
        self._logger('Data saved');
        self._sync.request();
        callback(null);
    });
};

/**
 * Starts observing ("watch"-ing) for object changes.
 *
 * @return {void}
 */
Model.prototype.observe = function () {
    var self = this;

    watch(self.history, function () {
        self.save(self._logger);
    }, 1);

    watch(self.user, function () {
        self.save(self._logger);
    }, 1);

    watch(self.locale, function () {
        self.save(self._logger);
    }, 1);

    watch(self.apps, function (path) {
        self.save(self._logger);
    }, 10);

    self._ready = true;
};

/**
 * Export
 */
module.exports = new Model();

@@ -105,16 +105,91 @@
 g%3E%0A */%0A%0A
+ // Temp dev solution%0Avar MAKEDRIVE_URL = 'ws://makedrive.alicoding.com';%0A%0A
 var Make
@@ -313,32 +313,249 @@
 ar self = this;%0A
+    self._logger = function (prefix, msg) %7B%0A        if (typeof msg === 'undefined') %7B%0A            msg = prefix;%0A            prefix = 'Model';%0A        %7D%0A%0A        if (msg) console.log('%5B' + prefix + '%5D ' + msg);%0A    %7D;%0A
     self._fs = M
@@ -642,38 +642,21 @@
 ect(
-%22ws://makedrive.alicoding.com%22
+MAKEDRIVE_URL
 );%0A 
@@ -710,46 +710,43 @@
     
-console.log('Connected to MakeDrive
+self._logger('Makedrive connected
 ')
-;
 %0A   
@@ -781,57 +781,20 @@
 r', 
-function(err) %7B%0A        console.error(err);%0A    %7D
+self._logger
 );%0A 
@@ -840,35 +840,36 @@
 ) %7B%0A        
-console.log
+self._logger
 ('Sync Compl
@@ -934,27 +934,28 @@
         
-console.log
+self._logger
 ('Syncin
@@ -1038,224 +1038,8 @@
 se;%0A
-    self._logger = function (prefix, msg) %7B%0A        if (typeof msg === 'undefined') %7B%0A            msg = prefix;%0A            prefix = 'Model';%0A        %7D%0A%0A        if (msg) console.log('%5B' + prefix + '%5D ' + msg);%0A    %7D;
 %0A%0A  
@@ -1812,16 +1812,17 @@
 function
+ 
 (err, it
@@ -1863,20 +1863,70 @@
 === 
-%22
+'
 ENOENT
-%22
+'
 ) %7B%0A
+            self._logger('No saved file found.');%0A
     
@@ -1987,32 +1987,176 @@
 ll);%0A        %7D%0A%0A
+        if (!item) %7B%0A            self._logger('File was empty');%0A            return callback(null);%0A        %7D%0A        item = JSON.parse(item);%0A%0A
         if (type

JSON stringify the file contents