import type { VNode } from 'vue';
import type { ValidationState } from '../../common/static-wrappers/interfaces/validation-interface';
import type { GeoJSON } from '../../data/geo';
import { Prop, toNative } from 'vue-facing-decorator';
import TsxComponent, { Component } from '../../app/vuetsx';
import TextArea from './textarea';

interface GeoJsonEditorArgs {
	value: GeoJSON;
	label?: string | VNode;
	validationState?: ValidationState;
	wrap?: boolean;
	changed: (e: GeoJSON) => void;
}

@Component
class GeoJsonEditorComponent extends TsxComponent<GeoJsonEditorArgs> implements GeoJsonEditorArgs {
	@Prop() value: GeoJSON;
	@Prop() label!: string | VNode;
	@Prop() wrap!: boolean;
	@Prop() changed: (e: GeoJSON) => void;

	getCurrentJSON(): string {
		if (this.value != null) {
			return JSON.stringify(this.value);
		}

		return '';
	}

	handleJsonValueChanged(e: string): void {
		let parsedObj: GeoJSON;
		try {
			parsedObj = JSON.parse(e);
		} catch (error) {}

		if (parsedObj != null) {
			this.changed(parsedObj);
		}
	}

	render(h) {
		return (
			<TextArea
				rows={4}
				label="Geo JSON"
				value={this.getCurrentJSON()}
				changed={(e) => {
					this.handleJsonValueChanged(e);
				}}
			/>
		);
	}
}

const GeoJsonEditor = toNative(GeoJsonEditorComponent);
export default GeoJsonEditor;
