import React, { useEffect, useRef, useState } from 'react'
import L from 'leaflet'

import "leaflet/dist/leaflet.css";
import icon from "leaflet/dist/images/marker-icon.png";
import iconShadow from "leaflet/dist/images/marker-shadow.png";

let DefaultIcon = L.icon({
iconUrl: icon,
shadowUrl: iconShadow,
});

export default function MapArray( { array } ) {
    console.log('map-array:MapArray: array.lngth: ' + array.length);

    /*center map in the middle of RVB*/
    const mapCenter = [52.16594, 10.52673];

    const mapRef = useRef();

    useEffect(() => {

	//base layer
	const baseLayerOsm = L.tileLayer(
	    "http://{s}.tile.osm.org/{z}/{x}/{y}.png",
	    {
                attribution: '&copy; <a href="http://osm.org/copyright">OpenStreetMap</a> contributors',
		maxZoom: 18,
		scrollWheelZoom: false,
	    }
	);

	//marker array
	const rryMrkr = array.map( function( value, key ) {

	    //console.log('map-array:MapArray:map() value: ' +JSON.stringify(value));

	    L.Marker.prototype.options.icon = DefaultIcon;
	    const marker = L.marker(
		[value.lat, value.lon],
		{alt: 'marker name: ' + value.name}
	    );
	    const popupText ='name: <b>' + value.name + '</b><br />lat: ' + value.lat + '<br />lon: ' + value.lon;
	    //console.log('popupText: ' + popupText);
	    marker.bindPopup(popupText);
	    return marker
	});
	console.log('rryMrkr: ' + rryMrkr.length);

	//layer group
	const overlayMrkr = L.layerGroup(rryMrkr);

	//map
        const map = L.map(
	    mapRef.current,
	    {attributionControl: true,
	     layers : [baseLayerOsm, overlayMrkr]}
	).setView(
	    mapCenter,
	    3
	);

	//layout control
	var baseMaps = {
	    "OpenStreetMap": baseLayerOsm
	};
	var overlayMaps = {
	    'Markers' : overlayMrkr
	};
	const layerControl = L.control.layers(baseMaps, overlayMaps).addTo(map);

	// unmount map function
	//You should unmount the function in react.js to remove the existing map.
	return () => map.remove();
    }, []);    

    if ( array !== undefined && array !== null && array.length > 0 ) {
	return (
	    <>
		<p>MapArray</p>
		<div
		    style={{padding: 0, margin: 0, width: "75%", height: "23vh",}}
		    ref={el => mapRef.current = el}>
		</div>
	    </>
	);
    }else{
	//TODO Why does mapRef have to be present?
	return (
            <>
		<p>MapArray loading...</p>
		<div
		    ref={el => mapRef.current = el}>
		</div>
            </>
	);
    }

};
//https://github.com/azaharyan/react-leaflet-example
