///<reference path=".#ts/client.d.ts" />

interface Templates {
	contentPage: Template;
}

Template.contentPage.helpers({

	page: function(){

		var section = Content.Section.db.findOne({handle: Session.get('contentMenuSectionHandle')});
		if (!section) {
			return;
		}

		return Content.fetchLocalizedPage({
			handle: Session.get('pageName'),
			section: section,
		});
	},

	pageReady: function(){
		return Session.get('pageReady');
	}
});


Template.contentPage.onRendered(function() {
	this.autorun(() => {
		this.subscribe('Content.Section', {handle: Session.get('contentMenuSectionHandle')});

		if(!Session.get('pageName')){

			Session.set('pageReady', false);
			this.cpsub = Meteor.subscribe('Content.Page', {
				section: Content.Section.db.findOne({handle: Session.get('contentMenuSectionHandle')}),
				device: Content.Device.PHONE,
				active: true,
				publishDate: {$lt: new Date()},
				publishEndDate: {$gt: new Date()},
			}, {sort: {publishDate: -1}, limit: 1, fields: {handle: 1, section: 1}});
		}
		else{
			var pgSelector = {
				handle: Session.get('pageName'),
				device: Content.Device.PHONE
			};

			this.cpsub = Meteor.subscribe('Content.Page', pgSelector);
			if(this.cpsub.ready()) {
				var page = Content.fetchLocalizedPage({handle: Session.get('pageName')});
				if(page == undefined) {
					Pages.redirect('/' + Session.get('contentMenuSectionHandle') + '/404');
				}
			}
			Session.set('pageReady', this.cpsub.ready());
		}
	});

	this.autorun(() => {
		if(this.cpsub.ready()) {
			var firstPage = Content.fetchLocalizedPage({
				section: Content.Section.db.findOne({handle: Session.get('contentMenuSectionHandle')})
			}, {sort: {publishDate: -1}});

			if (firstPage && !Session.get('pageName')) {
				Pages.redirect('/' + Session.get('contentMenuSectionHandle') + '/' + firstPage.handle);
			}
		}
	})
});