<template>
	<el-dialog :title="$t('CodeSyncServe')" width="70%" :visible.sync="visible"
	           :append-to-body="true"
	           custom-class="code-sync-serve-dialog"
	>
		<div>
			<el-form label-position="right" label-width="100px" size="mini">
				<el-form-item :label="$t('Auto launch')">
					<el-switch v-model="config.autoLaunch"/>
				</el-form-item>
				<el-form-item label="IP">
					<el-input v-model="config.ip"/>
				</el-form-item>
				<el-form-item label="Port">
					<el-input-number v-model="config.port" controls-position="right" :max="65535"/>
				</el-form-item>
			</el-form>
		</div>
		<div slot="footer" class="dialog-footer">
			<div>
				<el-switch :value="enabled" @input="onEnableServer"/>
				<span class="status">{{$t(status)}}</span>
			</div>
			<div>
				<el-button size="mini" @click="onClose">{{$t('Close')}}</el-button>
				<el-button size="mini" @click="onSave" type="primary">{{$t('Save')}}</el-button>
			</div>
		</div>
	</el-dialog>
</template>

<script>
	import {mapMutations, mapState} from 'vuex'
	import EnabledSetter from "../components/EnabledSetter";
	import {clonePureObj} from "../../../utils";
	import {codeSyncServeEnabled, startCodeSyncServe, stopCodeSyncServe} from "../../../code-sync-serve";
	import events from '../../../global-events';

	export default {
		name: "CodeSyncServeDialog",
		components: {EnabledSetter,},
		data() {
			return {
				visible: false,
				config: {},
				enabled: codeSyncServeEnabled,
			}
		},
		mounted() {
			events.$on('code-sync-status', this.onStatusChange);
		},
		destroyed() {
			events.$off('code-sync-status', this.onStatusChange);
		},
		computed: {
			status() {
				return this.enabled ? 'Running status' : 'Stop status';
			},
			...mapState({
				codeSyncServeConfig(state) {
					return state.editor.codeSyncServeConfig;
				}
			})
		},
		methods: {
			show() {
				this.config = clonePureObj(this.codeSyncServeConfig);
				this.visible = true;
			},
			onSave() {
				this.saveCodeSyncServeConfig(this.config);
				this.visible = false;
			},
			onClose() {
				this.visible = false;
			},
			onStatusChange(v) {
				this.enabled = v;
			},
			onEnableServer(v) {
				if (v) {
					startCodeSyncServe(this.config);
				} else {
					stopCodeSyncServe();
				}
				this.enabled = v;
			},
			...mapMutations([
				'saveCodeSyncServeConfig',
			]),
		}
	}
</script>

<style scoped>

</style>