(function () {
	'use strict';

    var template = require('../../../html/includes/new_page_modal.directive.html');

    var ng_module_name = 'new_page';

	angular.module(ng_module_name)
		.directive('newPage', newPage);

	newPage.$inject = ['$timeout', 'newPageService', 'growl.service', 'trashcanService', 'trashcanPreloadFactory'];
	function newPage($timeout, newPageService, growlService, trashcanService, trashcanPreload)
	{
		return {
			replace: false,
			restrict: 'E',
			controller: controller,
			controllerAs: 'newPage',
			templateUrl: template
		};

		function controller()
		{
			var ctrl = this;

			// "Constants" for radio buttons
			ctrl.SOURCE_NEW = 'new';
			ctrl.SOURCE_COPY = 'copy';

			ctrl.data = {};
			ctrl.source = ctrl.SOURCE_NEW;
			ctrl.source_page = 0;
			ctrl.copyablePages = [];

			// While this is false, editing the title can generate the address
			ctrl.addressFixed = false;

            trashcanService.setUrls(trashcanPreload.existingUrlInfo);
            ctrl.existingUrlInfo = trashcanService.urls;

			ctrl.init = function(copyablePages)
			{
				ctrl.setCopyablePages(copyablePages);
			};

			ctrl.setCopyablePages = function(copyablePages)
			{
				ctrl.copyablePages = copyablePages;
				var first = ctrl.copyablePages.shift();
				if (typeof first !== 'undefined')
				{
					ctrl.source_page = first.page_id;
				}
				ctrl.copyablePages.unshift(first);
			};

			ctrl.onSourceChange = function()
			{
				if (ctrl.source === ctrl.SOURCE_COPY)
				{
					$timeout(function()
					{
						angular.element('#copyable_pages').select2();
					}, 0);
				} else if (ctrl.source === ctrl.SOURCE_NEW)
				{
					angular.element('#copyable_pages').select2('destroy');
				}
			};

			ctrl.getSourcePageUrl = function()
			{
				var url = '';
				for (var i = 0; i < ctrl.copyablePages.length; i++)
				{
					if (ctrl.copyablePages[i].page_id === ctrl.source_page)
						url = ctrl.copyablePages[i].full_url;
				}

				return '/pages/' + url;
			};

			ctrl.show = function()
			{
				newPageService.getLatestCopyablePages(function(pages)
				{
					ctrl.setCopyablePages(pages);
				});


				ctrl.data = newPageService.data;
				ctrl.source = ctrl.SOURCE_NEW;
                ctrl.addressFixed = false;
                ctrl.invalidUrlDeleted = false;
                ctrl.isValidUrl = true;

				ctrl.onSourceChange();
				angular.element('#pageCreateModal').modal();
			};

			ctrl.hide = function()
			{
				angular.element('#pageCreateModal').modal('hide');
			};

			ctrl.submit = function()
			{
				if (ctrl.source === ctrl.SOURCE_NEW)
					ctrl.source_page = 0;

				ctrl.data.clone_source = parseInt(ctrl.source_page);

				var result = ctrl.validate();
				if (result === true)
				{
					newPageService.submit();
				} else
				{
					growlService.showError(result);
				}
			};

			ctrl.validate = function()
			{
				// Quick rejections
				if (ctrl.data.title.length === 0)
					return lmsg('pages.sites.error.no_title');
				if (ctrl.data.address_fragment.length === 0)
					return lmsg('pages.sites.error.no_url');
				if (ctrl.data.address_fragment[0] === '.')
					return lmsg('pages.url.error.invalid_characters');

				return true;
			};

			ctrl.showTitleChanged = function()
			{
				if (!ctrl.data.show_title)
					ctrl.data.show_menu = false;
			};

			ctrl.onTitleChange = function() {
				if (!ctrl.addressFixed)
				{
					ctrl.data.address_fragment = generateSlug(ctrl.data.title);
                    ctrl.checkUrl(ctrl.data.address_fragment);
				}
			};

			ctrl.onAddressChange = function() {
				ctrl.addressFixed = true;
                ctrl.checkUrl(ctrl.data.address_fragment);
			};

            ctrl.checkUrl = function(url) {
                // Pull out subentries
                var urls = [];
                for (var key in ctrl.existingUrlInfo)
                {
                    if ((ctrl.existingUrlInfo.hasOwnProperty(key))
                        && (ctrl.existingUrlInfo[key].parent_id === ctrl.data.parent_id))
                    {
                        urls.push({
                            url: ctrl.existingUrlInfo[key].url.split('/').pop(),
                            is_deleted: ctrl.existingUrlInfo[key].is_deleted
                        })
                    }
                }

                ctrl.isValidUrl = true;

                for (var i = 0; i < urls.length; i++)
                {
                    if (urls[i].url === url) {
                        ctrl.isValidUrl = false;
                        ctrl.invalidUrlDeleted = urls[i].is_deleted;
                    }
                }
            }

			newPageService.registerDisplayCallback(ctrl.show);
			newPageService.registerHideCallback(ctrl.hide);
		}
	}

	function generateSlug(title) {
		var length_limit = 40;

		var rus = {'а':'a', 'б':'b', 'в':'v', 'г':'g', 'д':'d', 'е':'e', 'ё':'jo', 'ж':'zh', 'з':'z', 'и':'i', 'й':'j', 'к':'k', 'л':'l', 'м':'m', 'н':'n', 'о':'o', 'п':'p', 'р':'r', 'с':'s', 'т':'t', 'у':'u', 'ф':'f', 'х':'h', 'ц':'c', 'ч':'ch', 'ш':'sh', 'щ':'sch', 'ъ':'', 'ы':'y', 'ь':'', 'э':'e', 'ю':'ju', 'я':'ja'};
		var pattern = /[^a-zA-Z0-9_]/g;

		title = title.toLowerCase();
		var slug  = '';
		for (var i = 0; i < title.length; i++)
		{
			var charact = title.substring(i, i + 1);
			if (rus[charact])
				slug += rus[charact];
			else
				slug += charact;
		}

		if (slug.match(pattern))
			slug = slug.replace(pattern, "_");

		if (slug.length > length_limit)
			slug = slug.substring(0, length_limit);

		return slug;
	}
}());
