(function () {
	'use strict';

    var ng_module_name = 'pageurl_list';

	angular.module(ng_module_name)
		.service('pageurlListService', pageurlListService);

	pageurlListService.$inject = ['$http', 'growl.service', 'trashcanService'];
	function pageurlListService($http, growl, trashcanService)
	{
		var service = this;

		service.pageurls = [];
		service.perms = {
			canEdit: false,
			canDelete: false
		};
		service.dataCallback = null;

		// Returns a reference to the tile list. Note that this is a reference and may be updated later once the
		// list is loaded (i.e. it will be empty when the page first loads).
		service.getUrls = function()
		{
			return service.pageurls;
		};

		service.setUrls = function(urls)
		{
			service.pageurls.length = 0;
			for (var i = 0; i < urls.length; i++)
			{
				service.pageurls.push(urls[i]);
			}
			if (service.pageurls.length === 0)
                service.pageurls[0] = {id: 0, children: []};


			if (service.dataCallback !== null)
				service.dataCallback();
		};

		service.setPerms = function(perms)
		{
			service.perms.canEdit = perms.canEditContent;
			service.perms.canDelete = perms.canDeleteContent;
		};

		service.getPerms = function()
		{
			return service.perms;
		};

		service.addPage = function(data, successCallback)
		{
			$http.post('/api/pages/menu/addpage', data)
				.then(function(result)
				{
					if (!result.data.success)
					{
						growl.showError(result.data.message);
						return;
					}

					// Merge the result into the local url list
					var url = result.data.menuitem;
					url.children = [];

					if (url.parent_id === service.pageurls[0].id)
					{
						service.pageurls[0].children.push(url);
					} else
					{
						for (var i = 0; i < service.pageurls[0].children.length; i++)
						{
							if (url.parent_id === service.pageurls[0].children[i].id)
								service.pageurls[0].children[i].children.push(url);
						}
					}

                    // Register with the trashcan service to show the url is no longer available
                    trashcanService.add(url.id, url.parent_id, url.full_url);

					growl.showSuccess(result.data.message);

					successCallback();
				}, function(result)
				{
					if ((typeof result.data === 'object') &&
						(typeof result.data.message === 'string'))
						growl.showError(result.data.message);
					else
						growl.showError(result);
				});
		};

		service.editLink = function(data, successCallback)
		{
			var url = '/api/pages/menu/addlink';
			var method = 'POST';
			if (data.id > 0)
			{
				url = '/api/pages/menu/' + data.id + '/edit_link';
				method = 'PUT';
			}

			$http({
					url: url,
					method: method,
					data: data
				})
				.then(function(result)
				{
					if (!result.data.success)
					{
						growl.showError(result.data.message);
						return;
					}

					// Merge the result into the local url list
					var url = result.data.menuitem;
					url.children = [];

					if (data.id > 0)
					{
						for (var i = 0; i < service.pageurls[0].children.length; i++)
						{
							if (url.id === service.pageurls[0].children[i].id)
							{
								service.pageurls[0].children[i].title = url.title;
								service.pageurls[0].children[i].link_url = url.link_url;
								service.pageurls[0].children[i].new_window = url.new_window;
							} else
							{
								for (var j = 0; j < service.pageurls[0].children[i].children.length; j++)
								{
									if (url.id === service.pageurls[0].children[i].children[j].id)
									{
										service.pageurls[0].children[i].children[j].title = url.title;
										service.pageurls[0].children[i].children[j].link_url = url.link_url;
										service.pageurls[0].children[i].children[j].new_window = url.new_window;
									}
								}
							}
						}
					} else
					{
						if (url.parent_id === service.pageurls[0].id)
						{
							service.pageurls[0].children.push(url);
						} else
						{
							for (i = 0; i < service.pageurls[0].children.length; i++)
							{
								if (url.parent_id === service.pageurls[0].children[i].id)
									service.pageurls[0].children[i].children.push(url);
							}
						}
					}

					growl.showSuccess(result.data.message);

					successCallback();
				}, function(result)
				{
					if ((typeof result.data === 'object') &&
						(typeof result.data.message === 'string'))
						growl.showError(result.data.message);
					else
						growl.showError(result);
				});
		};

		service.toggleVisibility = function(pageUrl)
		{
			var endpoint = '/api/pages/menu/' + pageUrl.id + '/' + (pageUrl.is_visible ? 'hide' : 'show');
			var onSuccess = !pageUrl.is_visible;
			$http.put(endpoint)
				.then(function(result)
				{
					if (!result.data.success)
					{
						growl.showError(result.data.message);
						return;
					}

					pageUrl.is_visible = onSuccess;
					for (var i = 0; i < pageUrl.children.length; i++)
					{
						pageUrl.children[i].is_visible = onSuccess;
					}
					growl.showSuccess(result.data.message);
				}, function(result)
				{
					if ((typeof result.data === 'object') &&
						(typeof result.data.message === 'string'))
						growl.showError(result.data.message);
					else
						growl.showError(result);
				});
		};

		service.deletePageurl = function(data, successCallback)
		{
			$http.delete('/api/pages/menu/' + data.id)
				.then(function(result)
				{
					if (!result.data.success)
					{
						growl.showError(result.data.message);
						return;
					}

					// Remove the item(s) from the menu
					// Note: .splice() reindexes the array so we need to find the item then delete it after
					// the loop instead of directly when we find it
					var found = -1;
					for (var i = 0 ; i < service.pageurls[0].children.length; i++)
					{
						if (data.id === service.pageurls[0].children[i].id)
						{
							found = i;
						} else
						{
							var url = service.pageurls[0].children[i];
							var childFound = -1;
							for (var j = 0 ; j < url.children.length; j++)
							{
								if (data.id === url.children[j].id)
								{
									childFound = j;
								}
							}
							if (childFound >= 0)
								url.children.splice(childFound,1);
						}
					}
					if (found >= 0)
                    {
                        // Let the trashcan service known that this has been deleted
                        trashcanService.delete(service.pageurls[0].children[found].id);

						service.pageurls[0].children.splice(found,1);
                    }

					growl.showSuccess(result.data.message);
					successCallback();
				},function(result)
				{
					if ((typeof result.data === 'object') &&
						(typeof result.data.message === 'string'))
						growl.showError(result.data.message);
					else
						growl.showError(result);
				});
		};

		service.orderChanged = function(pageUrl, callbackFunc)
		{
			$http.put('/api/pages/menu/' + pageUrl.id + '/order_changed', {display_order: pageUrl.display_order})
				.then(function(result)
				{
					// Do this even if there was an error because it acts as a rollback
					service.setUrls(result.data.menu_items);

					if (!result.data.success)
						growl.showError(result.data.message);

					callbackFunc();
				}, function(result)
				{
					if ((typeof result.data === 'object') &&
						(typeof result.data.message === 'string'))
						growl.showError(result.data.message);
					else
						growl.showError(result);
				});
		};

		service.itemMoved = function(pageUrl, callbackFunc)
		{
			$http.put('/api/pages/menu/' + pageUrl.id + '/item_moved', {parent_id: pageUrl.parent_id, display_order: pageUrl.display_order})
				.then(function(result)
				{
					// Do this even if there was an error because it acts as a rollback
					service.setUrls(result.data.menu_items);

					if (!result.data.success)
						growl.showError(result.data.message);

					callbackFunc();
				}, function(result)
				{
					if ((typeof result.data === 'object') &&
						(typeof result.data.message === 'string'))
						growl.showError(result.data.message);
					else
						growl.showError(result);
				});
		};


		service.GetData = function(siteId, callBack)
		{

			$http.get('/api/pages/menu/tree/' + siteId, {
				headers: {
					'If-Modified-Since': '0',
					"Pragma": "no-cache",
					"Expires": -1,
					"Cache-Control": "no-cache, no-store, must-revalidate"
				}})
				.then(function(result)
				{
					service.setUrls(result.data.urls);
					service.setPerms(result.data.perms);
					callBack();

				}, function(result)
				{

				});
		};

		service.registerDataCallback = function(callback)
		{
			service.dataCallback = callback;
		};
	}
}());
