<template>
	<div class="h-12 text-2xl flex items-center">
		<h1 class="">Active Requests</h1>
	</div>
	<movie-list :movies="activeRequests" @onClickMovie="displayMovie"/>
	<movie-modal :tmdb-id="activeTmdb" @onClose="activeTmdb = undefined" @onCancel="removeMovieRequest"/>
</template>

<script lang="ts">
import type { IMovie, IMovieDetails } from "@autoplex-api/request";
import { Status } from "@autoplex/restful";
import { Action } from "../store";
import { defineComponent } from "vue";
import MovieList from "../components/MovieList.vue";
import MovieModal from "../components/modals/MovieModal.vue";

export default defineComponent({
	components: {
		MovieList,
		MovieModal
	},
	data() {
		return {
			activeRequests: <IMovie[]>[],
			activeTmdb: <number|undefined> undefined
		}
	},
	methods: {
		displayMovie(movie: IMovie, index: number) {
			this.activeTmdb = movie.tmdbId;
		},
		removeMovieRequest(movie: IMovieDetails) {
			let index = this.activeRequests.findIndex(request => request.tmdbId == movie.tmdbId);
			this.activeRequests.splice(index, 1);
		},
		async fetchRequests() {
			try {
				let [status, response] = await this.$store.dispatch(Action.ActiveMovieRequests, undefined);
				if (status !== Status.Ok) {
					throw new Error("Non-OK status returned: " + status);
				}
				this.activeRequests = response.result;
			} catch(e) {
				console.error("Failed to fetch active movie tickets", e);
			};
		}
	},
	mounted() {
		this.fetchRequests();
	}
});
</script>
