<template>
	<el-dialog :title="$t('Behavior Editor')" :visible.sync="visible" :before-close="beforeClose" @opened="onOpened"
	           :fullscreen="true" :close-on-click-modal="false" :close-on-press-escape="false"
	           :append-to-body="true" custom-class="flex-dialog behavior-editor-dialog">
		<behavior-editor v-if="editorReady" ref="behaviorEditor" class="full-size"></behavior-editor>
		<div slot="footer" class="dialog-footer">
			<div>

			</div>
			<div>
				<!--<el-button size="mini" @click="onSave(true)">{{$t('Save And Preview')}}</el-button>
				<el-button size="mini" type="primary" @click="onSave(false)">{{$t('Save And Close')}}</el-button>-->
				<el-badge :hidden="!showBadge" is-dot>
					<el-button size="mini" type="primary" @click="onSave()">{{$t('Save')}}</el-button>
				</el-badge>
			</div>
		</div>
	</el-dialog>
</template>

<script>
	import {mapState, mapMutations, mapActions} from 'vuex'
	import BehaviorEditor from "../behavior-editor/BehaviorEditor";
	import events from "@/global-events.js"
	import {clonePureObj} from "../../../utils";

	export default {
		name: "BehaviorEditorDialog",
		components: {BehaviorEditor},
		data() {
			return {
				visible: false,
				editorReady: false,
			}
		},
		computed: {
			...mapState({
				showBadge: state => state.behavior.dirty,
			}),
		},
		created() {
			events.$on('behaviorSave', (isPreview) => {
				this.onSave(isPreview)
			});
		},
		methods: {
			show(path, index) {
				this.path = path;
				this.index = index;
				//this.behaviors = behaviors;
				this.editorReady = false;
				this.visible = true;
			},
			async onSave() {
				this.behavior_save();
				/*for (let i = 0, li = this.behaviors.length; i < li; i++) {
					const b = this.behaviors[i];
					if (b.uuid === behavior.uuid) {
						this.$set(this.behaviors, i, behavior);
						break;
					}
				}*/
				this.$emit('change');
				this.visible = false;
			},
			beforeClose(done) {
				if (this.$store.state.behavior.dirty) {
					this.$confirm(this.$t('Save this behavior before'), this.$t('Alert'), {
						closeOnClickModal: false,
						closeOnPressEscape: false,
						confirmButtonText: this.$t('Save And Close'),
						cancelButtonText: this.$t('Still Close'),
						distinguishCancelAndClose: true,
						type: 'warning'
					}).then(() => {
						this.onSave();
						done();
					}).catch((action) => {
						switch (action) {
							case 'close':
								break;
							case 'cancel':
								done();
								break;
						}
					});
				} else {
					done();
				}
			},
			onOpened() {
				this.editorReady = true;

				this.$nextTick(this.startEdit);
			},
			startEdit() {
				this.$refs.behaviorEditor.edit(this.path, this.index);
			},
			...mapMutations([
				'behavior_cancel',
				'behavior_save',
			])
		}
	}
</script>

<style scoped>

</style>