/*
 * This file is part of OsmInEdit, released under ISC license (see LICENSE.md)
 *
 * Copyright (c) Adrien Pavie 2019
 * Copyright (c) Daimler AG 2019
 *
 * Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies.
 *
 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
 *
 */

import { Path, withLeaflet } from 'react-leaflet';
import { CircleMarker, DivIcon, GeoJSON, Icon, LayerGroup, Marker, Polygon, Polyline } from 'leaflet';
import deepEqual from 'fast-deep-equal';
import PubSub from 'pubsub-js';

const existingIcons = {};

// Icon handling load errors
const MyIcon = Icon.extend({
	_createImg: function (src, el) {
		el = el || document.createElement('img');
		el.src = src;
		el.onerror = () => {
			window.UNUSABLE_ICONS.add(el.src);
			el.style.display='none';
		};
		return el;
	}
});

/**
 * Styled layer is an extension of GeoJSON layer in order to manage advanced styling of geometries.
 *
 * @property {MapStyler} [styler] The map styler
 */
class StyledLayer extends Path {
	createLeafletElement(props) {
		if(window.CONFIG.map_zoom_control_marker){
			//clone data
			this.cahedFeatures = JSON.parse(JSON.stringify(props.data.features));

			//sub event
			PubSub.subscribe("map.zoom.changed", (msg, data) => {			
				this.leafletElement.clearLayers();
				this.props.data.features = this._filterData(data.zoom);
				this._populateLayer(this.leafletElement, this.props);	
				this._sortFeaturesZIndex(this.leafletElement);
			})

			//filter data
			props.data.features = this._filterData(props.leaflet.map.getZoom())
		}

		// Add some defaults
		const thatStyler = props.styler.getFeatureStyle.bind(props.styler);
		const myprops = Object.assign({}, {
			pointToLayer: (feature, latlng) => {
				const marker = new CircleMarker(latlng, thatStyler(feature));
				return marker;
			},
			onFeatureClick: (() => {}),
			onEachFeature: (feature, layer) => {
				layer.on("click", () => {
					PubSub.publish("body.select.feature", { feature: feature });
				});
			},
			style: thatStyler
		}, props);

		// Create the GeoJSON layer
		const lGeojson = this._populateLayer(new GeoJSON(null, this.getOptions(myprops)), myprops);

		return lGeojson;
	}

	componentDidMount() {
		super.componentDidMount();

		this._sortFeaturesZIndex(this.leafletElement);
	}

    componentWillUnmount(){
		this.leafletElement.clearLayers();

        PubSub.unsubscribe("map.zoom.changed")
    }

	updateLeafletElement(fromProps, toProps) {
		if(window.CONFIG.map_zoom_control_marker){
			//clone data
			this.cahedFeatures = JSON.parse(JSON.stringify(toProps.data.features));

			//filter data
			toProps.data.features = this._filterData(toProps.leaflet.map.getZoom())
		}
		// Add style property according to styler
		if(!toProps.style) {
			toProps = Object.assign({}, toProps, { style: toProps.styler.getFeatureStyle.bind(toProps.styler) });
		}

		//Style
		if(fromProps.styler !== toProps.styler) {
			this.setStyle(toProps.style);
		}
		else {
			this.setStyleIfChanged(fromProps, toProps);
		}

		//Data
		if(
			fromProps.data !== toProps.data
			&& !deepEqual(fromProps.data, toProps.data)
		) {
			this.leafletElement.clearLayers();
			this._populateLayer(this.leafletElement, toProps);
		}

		this._sortFeaturesZIndex(this.leafletElement);
	}

	/**
	 * filter data by zoom
	 * @private
	 */
	_filterData(zoom) {
		//zoom>=20 show all markers
		//zoom==19 show half markers
		//zoom==18 hide all text markers
		//zoom<=17 hide al markers

		//clone data
		let pp = JSON.parse(JSON.stringify(this.cahedFeatures));
		
		if (zoom === 19) {
			pp.map(f => {
				let ft = f;
				if(ft.properties.tags.show_type && ft.properties.tags.poi_no){
					if(ft.properties.tags.poi_no % 2 !== 0){
						ft.properties.tags.show_type = "none"
					}
				}
				if(ft.id.startsWith("node/")){
					if(ft.properties.tags.poi_no % 2 !== 0){
						ft.geometry.coordinates[0] = 20000
					}
				}
				return ft;
			});
		} else if (zoom === 18) {
			pp.map(f => {
				let ft = f;
				if(ft.properties.tags.show_type){
					if(ft.properties.tags.poi_no % 4 !== 0){
						ft.properties.tags.show_type = "none"
					}
					if(ft.properties.tags.show_type === "text"){
						ft.properties.tags.show_type = "none"
					}
				}
				if(ft.id.startsWith("node/")){
					if(ft.properties.tags.poi_no % 4 !== 0){
						ft.geometry.coordinates[0] = 20000
					}
				}
				return ft;
			});
		} else if (zoom <= 17) {
			pp.map(f => {
				let ft = f;
				if(ft.properties.tags.show_type){
					ft.properties.tags.show_type = "none"
				}
				if(ft.id.startsWith("node/")){
					ft.geometry.coordinates[0] = 20000
				}
				return ft;
			});
		}
		
		return pp
	}

	/**
	 * Sort features by size and type
	 * @private
	 */
	_sortFeaturesZIndex(layer) {
		// First, lines
		layer.eachLayer(l => {
			if(l.feature && l instanceof Polyline && !(l instanceof Polygon)) {
				l.bringToFront();
			}
		});
		// Last, nodes
		layer.eachLayer(l => {
			if(l.feature && l.feature.id.startsWith("node/")) {
				l.bringToFront();
			}
		});
	}

	/**
	 * Add icons of features
	 * @private
	 */
	_addIcons(layer) {
		if(this._featureIcons && layer.hasLayer(this._featureIcons)) {
			layer.removeLayer(this._featureIcons);
		}

		this._featureIcons = new LayerGroup();

		const layers = layer.getLayers();
		
		const featuresWithTexts = layers.filter(l => {
			return l.feature 
				&& l.feature.properties 
				&& l.feature.properties.tags 
				&& l.feature.properties.tags.show_type !== "none"
				&& (l.feature.properties.tags.name !== "" && l.feature.properties.tags.name !== "卫生间") 
				&& l.feature.geometry 
				&& l.feature.geometry.type 
				&& (l.feature.geometry.type === "MultiPolygon" || l.feature.geometry.type === "Polygon")
				&& (!this.props.selection || l.feature.id !== this.props.selection.id)
		})
		const textWidth = 500;
		const textHeight = 20;
		featuresWithTexts.forEach(l => {
			const coords = l.getLatLng ? l.getLatLng() : (l.getBounds ? l.getBounds().getCenter() : null);

			if(coords) {
				let name = l.feature.properties.tags.name;
				let type = l.feature.properties.tags.show_type;
				let two = l.feature.properties.tags.two_class;
				let div = this._createNameMarkerByType(name, type, two);
				let icon = new DivIcon({
					iconSize: [textWidth, textHeight],
					html: div,
					className: "area_name_marker"
				});

				let marker = new Marker(coords, { icon: icon, interactive: false });
				this._featureIcons.addLayer(marker);
			}
		});

		const featuresWithIcons = layers.filter(l => l.options && l.options.iconImage && (!this.props.selection || l.feature.id !== this.props.selection.id));
		const iconSize = 20;
		featuresWithIcons.forEach(l => {
			const iconUrl = window.EDITOR_URL + "img/icons/"+l.options.iconImage;
			const coords = l.getLatLng ? l.getLatLng() : (l.getBounds ? l.getBounds().getCenter() : null);

			if(coords && !window.UNUSABLE_ICONS.has(iconUrl)) {
				let icon = existingIcons[iconUrl];

				if(!icon) {
					icon = new MyIcon({
						iconUrl: iconUrl,
						iconSize: [iconSize,iconSize],
						iconAnchor: [iconSize/2,iconSize/2]
					});
					existingIcons[iconUrl] = icon;
				}

				let marker = new Marker(coords, { icon: icon, interactive: false });
				this._featureIcons.addLayer(marker);
			}
		});

		layer.addLayer(this._featureIcons);
	}

	/**
	 * Name marker create by type
	 * @private
	 */
	_createNameMarkerByType(name, type, two)
	{
		switch (type) {
			case "none":
				return null;
			case "text":
				return this._createDivIcon(name);
			case "icon_text":
				return this._createImageDivIcon(this._getTextIconSrc(two), name, false);
			case "icon_text_border":
				return this._createImageDivIcon(this._getTextIconSrc(two), name);
		
			default:
				return null;
		}
	}

	/**
	 * 
	 * @private
	 */
	_getTextIconSrc(two){
		let src = window.EDITOR_URL;
		switch (two) {
			//柜台
			case "180101":
			case "180102":
			case "180109":
				src += "img/icons/amenity_reception.png";
				break;
			//自助机，值机，销售终端
			case "180104":
			case "180105":
			case "180108":
				src += "img/icons/amenity_self_service_machine.png";
				break;
			//安检，海关，通道
			case "180201":
			case "180202":
				src += "img/icons/amenity_safty_check.png";
				break;
			//登机口
			case "180301":
				src += "img/icons/amenity_leave.png";
				break;
			//到达口
			case "180402":
				src += "img/icons/amenity_arrive.png";
				break;
			//行李打包，寄存，托运
			case "180501":
			case "180503":
			case "180505":
				src += "img/icons/amenity_luggage.png";
				break;
			//行李提取
			case "180502":
				src += "img/icons/amenity_luggage_cart.png";
				break;
			//出入口
			case "190206":
				src += "img/icons/amenity_inout.png";
				break;
			//问讯，服务台
			case "190401":
			case "190402":
				src += "img/icons/amenity_info.png";
				break;

			default:
				break;
		}
		// console.log(src, two);

		return src;
	}
	

	/**
	 * Create divIcon elememnt
	 * @private
	 */
	_createDivIcon(name)
	{
		let div = document.createElement('div');
		div.style.backgroundColor = "rgba(0, 0, 0, 0)";
		div.style.pointerEvents = "none";
		div.style.verticalAlign = "middle";
		div.style.textAlign = "center";
		div.style.color = "rgb(135, 36, 6)";
		div.style.textShadow = "1px 0px 0px #fff, -1px 0px 0px #fff, 0px 1px 0px #fff, 0px -1px 0px #fff";
		div.innerText = name;

		return div;
	}

	/**
	 * Create divIcon elememnt with img
	 * @private
	 */
	_createImageDivIcon(src, name, bordered = true)
	{
		let divOut = document.createElement('div');
		divOut.style.verticalAlign = "middle";
		divOut.style.textAlign = "center";

		let divMid = document.createElement('div');
		divMid.style.width = "auto";
		divMid.style.display = "inline-block";
		divMid.style.verticalAlign = "middle";
		divMid.style.textAlign = "left";
		divMid.style.textIndent = "3px";
		divMid.style.pointerEvents = "none";
		divMid.style.paddingRight = "5px";
		divMid.style.color = "rgb(135, 36, 6)";
		divMid.style.textShadow = "1px 0px 0px #fff, -1px 0px 0px #fff, 0px 1px 0px #fff, 0px -1px 0px #fff";
		// divMid.style.paddingBottom = "2px";
		if(bordered){
			divMid.style.backgroundColor = "beige";
			divMid.style.border = "solid";
			divMid.style.borderColor = "black";
			divMid.style.borderWidth = "1px";
			divMid.style.borderRadius = "8px";
		}
		divMid.innerText = name;
		
		let divIn = document.createElement('div');
		divIn.style.backgroundColor = "white";
		divIn.style.height = "20px";
		divIn.style.width = "20px";
		divIn.style.verticalAlign = "middle";
		divIn.style.textAlign = "left";
		divIn.style.pointerEvents = "none";
		divIn.style.marginLeft = "-5px";
		divIn.style.marginTop = "-1px";
		divIn.style.border = "solid";
		divIn.style.borderColor = "black";
		divIn.style.borderWidth = "1.5px";
		divIn.style.borderRadius = "12px";
		divIn.style.float = "left";
		
		let img = document.createElement('img');
		img.src = src;
		img.style.pointerEvents = "none";
		img.style.height = "16px";
		img.style.width = "16px";
		img.style.marginLeft = "-2px";
		img.style.marginTop = "-2px";

		divOut.append(divMid);
		divMid.append(divIn);
		divIn.append(img);
		return divOut;
	}


	/**
	 * Load content into the leaflet layer
	 * @private
	 */
	_populateLayer(layer, props) {
		layer.addData(props.data);
		this._addIcons(layer);
		return layer;
	}
}

export default withLeaflet(StyledLayer);
