/**
 *
 * A service to coordinate the add page modal between 2 directives.
 * It holds new page data that is shared to both of them and allows them to notify each other.
 *
 */


(function () {
	'use strict';

    var ng_module_name = 'new_page';

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

	newPageService.$inject = ['$http'];
	function newPageService($http)
	{
		var service = this;
		service.displayCallback = null;
		service.hideCallback = null;
		service.submitCallback = null;
		service.data = {};

		service.resetData = function()
		{
			service.data.parent_id = 0;
			service.data.parent_name = '';
			service.data.clone_source = 0;
			service.data.title = '';
			service.data.address_prefix = '';
			service.data.address_fragment = '';
			service.data.show_title = true;
			service.data.show_menu = true;
		};

		service.registerDisplayCallback = function(callback)
		{
			service.displayCallback = callback;
		};

		service.registerHideCallback = function(callback)
		{
			service.hideCallback = callback;
		};

		service.registerSubmitCallback = function(callback)
		{
			service.submitCallback = callback;
		};

		service.show = function()
		{
			if (service.displayCallback !== null)
				service.displayCallback();
		};

		service.hide = function()
		{
			if (service.hideCallback !== null)
				service.hideCallback();
		};

		service.submit = function()
		{
			var data = {
				parent_id: service.data.parent_id,
				title: service.data.title,
				url: service.data.address_fragment,
				show_title: service.data.show_title,
				show_menu: service.data.show_menu,
				clone_source: service.data.clone_source
			};
			if (service.submitCallback !== null)
				service.submitCallback(data);
		};

		service.setData = function(pageurl, site_name)
		{
			service.data.parent_id = pageurl.id;
			if (pageurl.level > 0)
				service.data.parent_name = pageurl.title;
			else
				service.data.parent_name = site_name;

			service.data.title = '';
			service.data.address_prefix = '/pages/' + pageurl.full_url + '/';
			service.data.address_fragment = '';
			service.data.show_title = true;
			service.data.show_menu = true;
			service.data.clone_source = 0;
		};

		service.getLatestCopyablePages = function(callback)
		{
			$http.get('/api/pages/page_templates', {}). then(function(response)
			{
				// Ignore failures
				if (response.status === 200)
				{
					callback(response.data);
				}
			});
		};

		service.resetData();
	}
}());