/**
 * Copyright (C) 2015 Laverna project Authors.
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 */
define(["q","underscore","localforage","sjcl"],function(e,t,n,r){"use strict";function o(){}return t.extend(o.prototype,{init:function(){if(!Modernizr.indexeddb)return new e;var t=e.defer(),n=this;return n.start().then(function(){setTimeout(function(){return t.resolve()},100)}),t.promise},start:function(){var e=this;return this.openDb("notes-db").then(function(n){return t.isNull(n)?void console.log("no migration is needed"):(e.db=n,e.migrate(n))}).fail(function(e){console.error("Migration:initialize",e)})},openDb:function(t){var n=window.indexedDB.open(t),r=e.defer();return n.onerror=function(e){console.error("Migration:openDb",e),r.reject(e)},n.onupgradeneeded=function(){n.result&&n.result.close(),r.resolve(null)},n.onsuccess=function(e){r.resolve(e.target.result)},r.promise},migrate:function(n){var r=["notes","notebooks","tags","files"],o=this,i=[];return t.each(r,function(e){i.push(function(){var t;try{t=n.transaction([e])}catch(r){return}return o.getData(t,e).then(function(t){return o.migrateStore(e,t)})})}),t.reduce(i,e.when,new e).then(function(){n.close()}).fail(function(e){console.error("Migration:migrate",e)})},migrateStore:function(r,o){var i=this,s=[],u=n.createInstance({name:"notes-db",storeName:r});return t.each(o,function(e){s.push(function(){return i.removeItem(r,u,e.id).then(function(){return i.saveForageItem(r,u,e)})})}),t.reduce(s,e.when,new e).then(function(){}).fail(function(e){console.error("Migration:migrateStore",e)})},saveForageItem:function(n,o,i){var s=e.defer();return t.isUndefined(i.notebookId)||(i.notebookId=i.notebookId.toString()),t.isUndefined(i.parentId)||(i.parentId=i.parentId.toString()),"files"===n&&(i.fileType=i.type,i.type="files"),"tags"===n&&(i.id=r.hash.sha256.hash(i.name.toString()).join("")),i=t.extend({type:n,created:Date.now(),updated:Date.now(),trash:0},i,{id:i.id.toString()}),o.setItem(i.id,i,function(e,t){return e?s.reject(e):s.resolve(t)}),s.promise},removeItem:function(t,n,r){if("tags"===t)return this.putToTrash.apply(this,arguments);if("notebooks"!==t||"string"==typeof r)return new e;var o=e.defer(),i=this.db.transaction([t],"readwrite").objectStore(t)["delete"](r);return i.onsuccess=function(){o.resolve()},i.onerror=function(e){o.reject(e)},o.promise},putToTrash:function(t,n,r){var o=e.defer(),i={id:r,type:"tags",name:r,trash:2,created:0,updated:0};return n.setItem(i.id,i,function(e,t){return e?o.reject(e):o.resolve(t)}),o.promise},getData:function(t,n){var r=e.defer(),o=t.objectStore(n).openCursor(),i={};return o.onerror=function(e){console.error("Migration:getData",e),r.reject(e)},o.onsuccess=function(e){var t=e.target.result;return t?(i[t.key]=t.value,void t["continue"]()):r.resolve(i)},r.promise}}),o});