<template>
	<div class="content has-text-centered">
		<h2>
			{{ welcomePrefix }}
			{{ userInfo.name !== "" ? userInfo.name : userInfo.username }}!
		</h2>
		<add-task
			:list="defaultList"
			@taskAdded="updateTaskList"
			class="is-max-width-desktop"
		/>
		<template v-if="!hasTasks">
			<p>You can create a new list for your new tasks:</p>
			<x-button
				:to="{ name: 'list.create', params: { id: defaultNamespaceId } }"
				:shadow="false"
				class="ml-2"
				v-if="defaultNamespaceId > 0"
			>
				Create a new list
			</x-button>
			<p class="mt-4" v-if="migratorsEnabled">
				Or import your lists and tasks from other services into Vikunja:
			</p>
			<x-button
				v-if="migratorsEnabled"
				:to="{ name: 'migrate.start' }"
				:shadow="false"
			>
				Import your data into Vikunja
			</x-button>
		</template>
		<ShowTasks :show-all="true" v-if="hasLists" :key="showTasksKey" />
	</div>
</template>

<script>
import { mapState } from 'vuex';
import ShowTasks from './tasks/ShowTasks';
import AddTask from '../components/tasks/add-task';
import ListModel from '../models/list';

export default {
	name: 'Home',
	components: {
		ShowTasks,
		AddTask,
	},
	data() {
		return {
			loading: false,
			currentDate: new Date(),
			tasks: [],
			defaultList: ListModel,
			updateWelcomeInterval: 1000,
			welcomePrefix: 'Hi',
			showTasksKey: 0,
		};
	},
	created() {
		this.defaultList = new ListModel();
		this.defaultList.id = 1;
	},
	mounted() {
		const timer = window.setTimeout(
			this.updateWelcome,
			this.updateWelcomeInterval,
		);
		this.$on('hook:destroyed', () => window.clearTimeout(timer));
	},
	computed: mapState({
		migratorsEnabled: state =>
			state.config.availableMigrators !== null &&
			state.config.availableMigrators.length > 0,
		authenticated: state => state.auth.authenticated,
		userInfo: state => state.auth.info,
		hasTasks: state => state.hasTasks,
		defaultNamespaceId: state => {
			if (state.namespaces.namespaces.length === 0) {
				return 0;
			}

			return state.namespaces.namespaces[0].id;
		},
		hasLists: state => {
			if (state.namespaces.namespaces.length === 0) {
				return false;
			}

			return state.namespaces.namespaces[0].lists.length > 0;
		},
	}),
	methods: {
		updateTaskList() {
			this.showTasksKey += 1;
		},
		updateWelcome() {
			this.currentDate = new Date();
			if (this.currentDate.getHours() < 12) {
				this.welcomePrefix = 'Good Morning';
			} else if (this.currentDate.getHours() < 17) {
				this.welcomePrefix = 'Good Afternoon';
			} else {
				this.welcomePrefix = 'Good Evening';
			}
			this.$options.timer = window.setTimeout(
				this.updateDateTime,
				this.updateWelcomeInterval,
			);
		},
	},
};
</script>
