'use strict';

angular.module("IndexedDb", [])
	.factory('IndexedDb', ["$q", "$rootScope", "$window", function($q, $rootScope, $window){
		var db;
		var ready;
		return {
			start: function(){
				var deferred = $q.defer();
				var request = window.indexedDB.open("FreeNews", 11);
				request.onerror = function(event){
					alert("Database error: " + event.target.errorCode);
					deferred.resolve(false);
				};
				request.onsuccess = function(event){
					console.log("Database ready");
					db = event.target.result;
					ready = true;
					deferred.resolve(true);
				};
				request.onupgradeneeded = function(event){
					console.log("request onupgradeneeded");
					var db = event.target.result;
					
					if(event.oldVersion < 8){
						var objectStore = db.createObjectStore("Subscriptions", { keyPath: "id", autoIncrement: true });
						objectStore.createIndex("id", "id", { unique: true });
						objectStore.createIndex("url", "url", { unique: true });
						var objectStore = db.createObjectStore("Articles", { keyPath: "id", autoIncrement: true });
						objectStore.createIndex("id", "id", { unique: true });
						objectStore.createIndex("title", "title", { unique: false });
						objectStore.createIndex("body", "body", { unique: false });
						objectStore.createIndex("date", "date", { unique: false });
						objectStore.createIndex("url", "url", { unique: true });
						objectStore.createIndex("image", "image", { unique: false });
						objectStore.createIndex("intro", "intro", { unique: false });
					}
					else if(event.oldVersion < 10){
						var objectStore = event.currentTarget.transaction.objectStore("Articles");
						objectStore.createIndex("subscriptions_id", "subscriptions_id", { unique: false });
					}
					else if(event.oldVersion < 11){
						var objectStore = event.currentTarget.transaction.objectStore("Subscriptions");
						objectStore.createIndex("title", "title", { unique: false });
					}
				};
				return deferred.promise;
			},
			ask: function(){
				var deferred = $q.defer();
				if(ready == true){
					deferred.resolve(true);
				}
				else{
					this.start().then(function(){
						deferred.resolve(true);
					});
					/*$rootScope.$on('Subscriptions-updated', function(e){
						deferred.resolve(true);
					});*/
				}
				return deferred.promise;
			},
			add: function(table, line){
				var deferred = $q.defer();
				
					var transaction = db.transaction([table], "readwrite");
					transaction.oncomplete = function(event) {
						console.log("transaction complete");
						deferred.resolve(true);
					};
					transaction.onerror = function(event) {
						console.log("transaction error");
						deferred.reject("transaction error");
					};
					transaction.objectStore(table).add(line);
					$rootScope.$broadcast(table + '-updated');
				
				return deferred.promise;
			},
			get: function(table){
				var deferred = $q.defer();
				
				var Data = [];
				var transaction = db.transaction([table], "readwrite");
				var objectStore = transaction.objectStore(table);
				objectStore.openCursor().onsuccess = function(event){
					var cursor = event.target.result;
					if(cursor){
						Data.push(cursor.value);
						cursor.continue();
					}
					else {
						//console.log(Subscriptions);
						deferred.resolve(Data);
					}
				};
				

				return deferred.promise;
			},
			getLine: function(table, id){
				var deferred = $q.defer();
				db.transaction([table], "readonly").objectStore(table).get(id).onsuccess = function(e){
					console.log(e.target);
					deferred.resolve(e.target.result);
				}
				return deferred.promise;
			},
			remove: function(table, id){
				var deferred = $q.defer();
				
				var Subscriptions = [];
				var deletion = db.transaction([table], "readwrite").objectStore(table).delete(id);
				deletion.onsuccess = function(event){
					$rootScope.$broadcast(table + '-updated');
					deferred.resolve(true);
				};

				return deferred.promise;
			}
			
		};
	}])
	.run(["IndexedDb", "$rootScope", "$window", function(IndexedDb, $rootScope, $window){
		IndexedDb.start().then(function(resp){
			$rootScope.$broadcast('database-ready');
		});
	}]);
