import VectorLayer from "ol/layer/Vector";
import VectorSource from "ol/source/Vector";
import Draw from 'ol/interaction/Draw';
import {
	Fill,
	Stroke,
	Style,
	Text as TextStyle
} from "ol/style";
import CircleStyle from "ol/style/Circle";
import {
	getArea,
	getLength
} from 'ol/sphere.js';

const serverUrl = 'https://app.hycdyzt.com';
const geoserverUrl = 'http://47.109.60.82:8080';
const mgServerUrl = 'http://47.109.60.82:9989/openApi'
const globalMap = {
	map: null
}
const formatArea = function(polygon) {
	const area = getArea(polygon, {
		projection: 'EPSG:4326'
	});
	let output;
	if (area > 10000) {
		output = Math.round((area / 1000000) * 100) / 100 + ' ' + 'k㎡';
	} else {
		output = Math.round(area * 100) / 100 + ' ' + '㎡';
	}
	return output;
};

const startMeasure = (map, callback) => {
	map.removeLayer(map.getAllLayers().find(l => l.get('id') === 'draw-layer'));
	const source = new VectorSource();

	const vector = new VectorLayer({
		id: 'draw-layer',
		source: source,
		style: feature => {
			const area = formatArea(feature.getGeometry());
			return new Style({
				fill: new Fill({
					color: 'rgba(255, 255, 255, 0.4)',
				}),
				stroke: new Stroke({
					color: '#ffcc33',
					width: 2,
				}),
				text: new TextStyle({
					text: area,
					"textBaseline": "middle",
					"font": "bold 10px/1 Verdana",
					"offsetX": 0,
					"offsetY": 0,
					fill: new Fill({
						color: 'rgba(0, 0, 0, 0.9)',
					}),
					"placement": "point",
					"maxAngle": 0.7853981633974483,
					"overflow": true,
					"rotation": 0
				})
			})
		}
	});

	const draw = new Draw({
		source: source,
		type: 'Polygon',
		stopClick: true,
		freehand: true,
		style: function(feature) {
			const area = formatArea(feature.getGeometry());
			console.log(feature.getGeometry().getCoordinates())
			return new Style({
				fill: new Fill({
					color: 'rgba(255, 255, 255, 0.2)',
				}),
				stroke: new Stroke({
					color: 'rgba(0, 0, 0, 0.5)',
					lineDash: [10, 10],
					width: 2,
				}),
				text: new TextStyle({
					text: area,
					"textBaseline": "middle",
					"font": "bold 10px/1 Verdana",
					"offsetX": 0,
					"offsetY": 0,
					fill: new Fill({
						color: 'rgba(0, 0, 0, 0.9)',
					}),
					"placement": "point",
					"maxAngle": 0.7853981633974483,
					"overflow": true,
					"rotation": 0
				}),
			});;
		},
	});
	map.addInteraction(draw);

	draw.on('drawend', function() {
		map.addLayer(vector)
		map.removeInteraction(draw);
		callback();
	});
}

export default {
	serverUrl,
	geoserverUrl,
	globalMap,
	mgServerUrl,
	startMeasure
}