import { createEffect, createResource, For, useContext, VoidComponent } from 'solid-js';
import { Circle, Fill, Stroke, Style } from 'ol/style';
import OlFeature from 'ol/Feature';
import OlPoint from 'ol/geom/Point';
import OlPolygon from 'ol/geom/Polygon';

import { Stop, StopShape } from '../types';
import { BusinessDataContext, BusinessDataStore } from "../businessData";
import { SearchContext, SearchStore } from "./searchStore";


// TODO: Use boolean to set MapStop selected
export const MapStop: VoidComponent<{ stop: Stop, selected: Stop | undefined }> = (props) => {
	const businessDataStore: BusinessDataStore | undefined = useContext(BusinessDataContext);
	const searchStore: SearchStore | undefined = useContext(SearchContext);
	if (businessDataStore === undefined || searchStore === undefined)
		return <div />;

	const { getStopShape } = businessDataStore;
	const { setMapFeature } = searchStore;

	const stopStyle = new Style({
		image: new Circle({
			fill: undefined,
			stroke: new Stroke({ color: '#3399CC', width: 1.5 }),
			radius: 10,
		}),
	});

	const selectedStopStyle = new Style({
		image: new Circle({
			fill: undefined,
			stroke: new Stroke({ color: 'purple', width: 2 }),
			radius: 10,
		}),
	});

	const stopAreaStyle = new Style({
		stroke: new Stroke({ color: 'red' }),
		fill: new Fill({ color: 'rgba(255,255,255,0.2)' }),
	});

	const getShape = async (stopId: number): Promise<StopShape | undefined> => {
		return await getStopShape(stopId);
	};
	const [shape] = createResource<StopShape | undefined, number>(props.stop.id, getShape);

	createEffect(() => {
		const shape_ = shape();

		if (shape_ === undefined) {
			return;
		}

		let feature = undefined;

		if (props.stop.epsg3857_x !== undefined && props.stop.epsg3857_y !== undefined) {
			const selectStopStyle = () => {
				return (props.selected?.id === props.stop.id ? selectedStopStyle : stopStyle);
			}
			feature = new OlFeature({
				geometry: new OlPoint([props.stop.epsg3857_x, props.stop.epsg3857_y]),
			});
			feature.setStyle(selectStopStyle);
		}

		else {
			let geometry = undefined;
			const areaShape = shape();
			if (areaShape !== undefined) {
				geometry = new OlPolygon([areaShape.epsg3857_points.slice(0, -1)]);
			}
			else {
				geometry = new OlPoint([props.stop.epsg3857_x, props.stop.epsg3857_y]);
			}
			feature = new OlFeature({ geometry: geometry });
			feature.setStyle(stopAreaStyle);
		}
		feature.setId(props.stop.id);

		setMapFeature(props.stop.id, feature);
	});

	return <For each={props.stop.stops}>{stop => <MapStop stop={stop} selected={props.selected} />}</For>;
}
