<template>
	<Dialog
		v-if="source"
		:options="{
			title: $t('Change {app} {version} branch', { app, version }),
			actions: [
				{
					label: this.$t('Change Branch'),
					variant: 'solid',
					loading: $resources.changeBranch.loading,
					onClick: () => changeBranch()
				}
			]
		}"
		v-model="show"
	>
		<template v-slot:body-content>
			<div v-if="$resources.branches.loading" class="mt-2 flex justify-center">
				<LoadingText />
			</div>
			<ErrorMessage
				v-else-if="$resources.branches.error"
				:message="$resources.branches.error"
			/>
			<select
				v-else-if="$resources.branches.data"
				class="form-select block w-full"
				v-model="selectedBranch"
			>
				<option v-for="branch in branchList()" :key="branch">
					{{ branch }}
				</option>
			</select>
		</template>
	</Dialog>
</template>

<script>
import { toast } from 'vue-sonner';
import { getToastErrorMessage } from '../../utils/toast';
import { DashboardError } from '../../utils/error';

export default {
	name: 'ChangeAppBranchDialog',
	data() {
		return {
			show: true,
			selectedBranch: null
		};
	},
	props: ['app', 'source', 'version', 'activeBranch'],
	emits: ['branch-changed'],
	resources: {
		branches() {
			return {
				url: 'jcloud.api.marketplace.branches',
				params: {
					name: this.source
				},
				auto: true
			};
		},
		changeBranch() {
			return {
				url: 'jcloud.api.marketplace.change_branch',
				params: {
					name: this.app,
					source: this.source,
					version: this.version,
					to_branch: this.selectedBranch
				},
				validate() {
					if (this.selectedBranch == this.activeBranch) {
						throw new DashboardError(this.$t('Please select a different branch'));
					}
				}
			};
		}
	},
	methods: {
		changeBranch() {
			toast.promise(this.$resources.changeBranch.submit(), {
				loading: this.$t('Updating version branch...'),
				success: () => {
					this.show = false;
					this.$emit('branch-changed');
					return this.$t('Branch changed successfully');
				},
				error: e => getToastErrorMessage(e)
			});
		},
		branchList() {
			if (this.$resources.branches.loading || !this.$resources.branches.data) {
				return [];
			}
			return this.$resources.branches.data.map(d => d.name);
		}
	},
	mounted() {
		this.selectedBranch = this.activeBranch;
	}
};
</script>