<template>
<div class="panel">

<template v-if="user">
<side-bar v-if="user" :role="user && user.status" :active="active">
</side-bar>

<div v-if="loading" class="page loading">
<span class="error" >{{loadingError}}</span>
<spinner></spinner>
</div>

<home :user="user" v-else-if="active == 1" />
<new-estimate :user="user" :fees="fees" v-else-if="active == 2" />
<estimates :user="user" :fees="fees" v-else-if="active == 3" />
<settings :user="user" v-else-if="active == 4" />
<sign-out :user="user" v-else-if="active == 5" />
</template>

<template v-if="!user && active == 6">
<login @login="start" />
</template>

</div>
</template>

<script>
import SideBar from "./sidebar.vue"
import Spinner from "./spinner.vue"
import Home from "./home.vue"
import NewEstimate from "./new.vue"
import Estimates from "./estimates.vue"
import Settings from "./settings.vue"
import SignOut from "./sign-out.vue"
import Login from "./login.vue"

function getCookie(name) {
	var re = new RegExp(name + "=([^;]+)")
	var value = re.exec(document.cookie)

	return (value != null) ? unescape(value[1]) : null
}

function refreshToken() {
	const token = getCookie("skouter")

	fetch(`/api/token`,
		{method: 'GET',
		headers: {
			"Accept": "application/json",
			"Authorization": `Bearer ${token}`,
			},
	}).then(response => {
		if (!response.ok) {
			console.log("Error refreshing token.")
		}
	})

	// Recursive refresh
	setTimeout(this.refreshToken, 1000*60*25)
}

function getUser() {
	const token = getCookie("skouter")

	return fetch(`/api/user`,
		{method: 'GET',
		headers: {
			"Accept": "application/json",
			"Authorization": `Bearer ${token}`,
    		},
	}).then(response => {
		if (response.ok) {
			return response.json()
		} else {
			// Redirect to login if starting token is invalid
			window.location.hash = '#login'
		}
	}).then (result => {
		if (!result || !result.length) return // Exit if token is invalid
		this.user = result[0]
	})

}

function getFees() {
	const token = getCookie("skouter")
	
	return fetch(`/api/fees`,
		{method: 'GET',
    		headers: {
        	"Accept": "application/json",
        	"Authorization": `Bearer ${token}`,
    		},
	}).then(response => {
		if (response.ok) { return response.json() }
	}).then (result => {
		if (!result || !result.length) return // Exit if token is invalid or no fees are saved
		this.fees = result
	})

}

// The default fees of a new loan. Percentage values take precedent over amounts
const fees = [
	{ name: 'Processing fee', type: 'Lender Fees', amount: 500, perc: 0 },
	{ name: 'Underwriting fee', type: 'Lender Fees', amount: 500, perc: 0 },
	{ name: 'Credit Report', type: 'Services Required by Lender',
	amount: 52.50 },
	{ name: 'Appraisal', type: 'Services Required by Lender', amount: 52.50 },
	{ name: 'Title Services', type: 'Title Company', amount: 1000 },
	{ name: 'Lender\'s Title Insurance', type: 'Title Company', amount: 1599 },
	{ name: 'Owner\'s Title Insurance', type: 'Title Company', amount: 451.00 },
	{ name: 'Recording Charges', type: 'Government', amount: 99.00 },
	{ name: 'State Tax', type: 'Government', amount: 2411.00 },
]

// Used to check the current section of the app generally without a regex match
// each time.
function active() {
	if (this.hash == '' || this.hash == '#') {
		return 1
	} else if (/^#new\/?/.exec(this.hash)) {
		return 2
	} else if (/^#estimates\/?/.exec(this.hash)) {
		return 3
	} else if (/^#settings\/?/.exec(this.hash)) {
		return 4
	} else if (/^#sign-out\/?/.exec(this.hash)) {
		return 5
	} else if (/^#login\/?/.exec(this.hash)) {
		return 6
	} else {
		return 0
	}
}

// Fetch data before showing UI. If requests fail, assume token is expired.
function start() {
	this.loading = true

	let loaders = []
	loaders.push(this.getUser())
	loaders.push(this.getFees())
	Promise.all(loaders).then((a, b) => {
		this.loading = false
		if (!b) {
			// Time untill token expiration may have elapsed before the page
			// reloaded
			this.refreshToken()
		}
	}).catch(error => {
		console.log("An error occured %O", error)
		this.loadingError = "Could not initialize app."
		window.location.hash = 'login'
	})

}


export default {
	components: {
		SideBar,
		Spinner,
		Home,
		NewEstimate,
		Estimates,
		Settings,
		SignOut,
		Login
	},
	computed: { active },
	methods: {
		getCookie,
		start,
		getUser,
		getFees,
		refreshToken,
	},
	data() {
		return {
			loading: true,
			user: null,
			hash: window.location.hash,
			fees: [],
			loadingError: "",
		}
	},
	created() {
		window.onhashchange = () => this.hash = window.location.hash
		this.token = this.getCookie("skouter")

		if (!this.token) {
			window.location.hash = 'login'
			this.loading = false
			return
		}
		this.start()
	}
}
</script>