<script>
import Project from './components/project.vue';
import Admin from './components/admin.vue';
import Upload from './components/upload.vue';

const aoRoutes = {
	'project': Project,
	'admin': Admin,
	'upload': Upload
};

export default {
	data() {
		return {
			hash: {},
			consts: this.spot.consts,
			user: this.spot.vars('user')
		};
	},
	provide() {
		return {
			projects: this.spot.vars('projects'),
			consts: this.consts,
			user: this.user
		};
	},
	inject: ['spot'],
	computed: {
		page() {
			this.spot.vars('page', this.hash.page);
			return aoRoutes[this.hash.page];
		}
	},
	created() {
		//User
		this.user.timezone = Intl.DateTimeFormat().resolvedOptions().timeZone || this.consts.default_timezone;
	},
	mounted() {
		window.addEventListener('hashchange', () => {this.onHashChange();});
		var oEvent = new Event('hashchange');
		window.dispatchEvent(oEvent);
	},
	methods: {
		_hash(hash, bReboot) {
			bReboot = bReboot || false;
			if(!hash) return window.location.hash.slice(1);
			else window.location.hash = '#'+hash;

			if(bReboot) location.reload();
		},
		onHashChange() {
			let asHash = this.getHash();
			if(asHash.hash !='' && asHash.page != '') {
				if(asHash.page == this.hash.page) this.spot.onSamePageMove(asHash);
				this.hash = asHash;
			}
			else if(!this.hash.page) this.setHash(this.spot.consts.default_page);
		},
		getHash() {
			let sHash = this._hash();
			let asHash = sHash.split(this.spot.consts.hash_sep);
			let sPage = asHash.shift() || '';
			return {hash:sHash, page:sPage, items:asHash};
		},
		setHash(sPage, asItems, bReboot) {
			bReboot = bReboot || false;
			sPage = sPage || '';
			asItems = asItems || [];
			if(typeof asItems == 'string') asItems = [asItems];

			if(sPage != '') {
				let sItems = (asItems.length > 0)?this.spot.consts.hash_sep+asItems.join(this.spot.consts.hash_sep):'';
				this._hash(sPage+sItems, bReboot);
			}
		}
	}
}
</script>
<template>
	<div id="main">
		<component :is="page" />
	</div>
	<div id="mobile"></div>
</template>