<template>
	<div
		v-if="!isLoading"
		class="box p-3"
	>
		<tabs-group @tabActivated="tabActivated">
			<tab-content title="Visual Editor">
				<div class="editor mt-2">
					<VueEditor
						v-model="page.content"
						:editor-options="editorOptions"
						:disabled="isVueEditorDisabled"
					/>
				</div>
			</tab-content>
			<tab-content title="Raw Content">
				<div>
					<textarea
						v-model="page.content"
						class="p-fluid pages-editor-raw"
					/>
				</div>
			</tab-content>
		</tabs-group>
		<button
			class="btn btn-primary mt-3 mb-2"
			@click="saveContent"
		>
			Save
		</button>
	</div>
	<div v-else>
		<i class="fa fa-spinner fa-spin fa-3x fa-fw"/>
		<span class="sr-only">Loading …</span>
	</div>
</template>

<script>

import axios from 'axios'

// Basic Use - Covers most scenarios
// https://github.com/davidroyer/vue2-editor => docs apply for version 3, too
import { VueEditor } from 'vue3-editor'

import hljs from 'highlightjs'
import 'highlightjs/styles/dracula.css'

import TabsGroup from '@/components/tabs/TabsGroup'
import TabContent from '@/components/tabs/TabContent'

export default {
	name: 'PagesEdit',
	components: {
		VueEditor,
		TabsGroup,
		TabContent
	},
	data: () => ({
		page: null,
		isLoading: true,
		isVueEditorDisabled: false,
		editorOptions: {
			modules: {
				syntax: {
					highlight: (text) => hljs.highlightAuto(text).value
				}
			},
			theme: 'snow'
		}
	}),
	beforeMount() {
		const { slug } = this.$route.params

		axios
			.get(`/api/pages?slug=${slug}`)
			.then((response) => {
				[this.page] = response.data['hydra:member']
				this.isLoading = false
			})
	},
	methods: {
		saveContent() {
			axios
				.put(`/api/pages/${this.page.id}`, this.page)
				.then(() => {
					this.$router.push({
						name: 'Pages',
						params: { slug: this.page.slug }
					})
				})
		},
		tabActivated(name) {
			this.isVueEditorDisabled = name === 'Raw Content'
		}
	}
}
</script>
