import React, {useEffect,useState} from 'react';
import axios from 'axios';
import qs from 'qs';

import Map from '../components/map/map';

const data = qs.stringify(
    {
	'data': '[bbox:51.990800124058914,10.045623779296875,52.552976197007524,11.01104736328125][out:json];(node["shop"="second_hand"];way["shop"="second_hand"];relation["shop"="second_hand"];);out center;'
    }
);

//TODO Make fields available via configuration!
const interval=3600000;
const opInstance='https://overpass-api.de/api/interpreter';
const opInstanceZ='https://z.overpass-api.de/api/interpreter';
const config = {
    method: 'post',
    maxBodyLength: Infinity,
    url: opInstanceZ,
    headers: {
	'Content-Type': 'application/x-www-form-urlencoded'
    },
    data : data
};

function parseOsmElem(response){
    let elemAry=[];
    if(response.data){
	let elements=response.data.elements;
	let no=elements.length;
	//console.log('no: '+no);
	for(let i = 0; i < no; i++) {
	    let elemObj={};
	    elemObj.id=elements[i].id;
	    elemObj.name=elements[i].tags.name;
	    if(elements[i].tags.name===undefined){
		//TODO Handle issue!
		console.error('ERROR: OSM element does NOT include name tag');
	    }else if(elements[i].type==='node'){
		elemObj.lat=elements[i].lat;
		elemObj.lon=elements[i].lon;
	    }else if(elements[i].type==='way'){
		elemObj.lat=elements[i].center.lat;
		elemObj.lon=elements[i].center.lon;
	    }else{
		console.error('ERROR: OSM element NOT supported');
	    }
	    //console.log('elem name: '+elemObj.name);
	    //console.log('elem lat: '+elemObj.lat);
	    //console.log('elem lon: '+elemObj.lon);
	    elemAry.push(elemObj);
            //console.error('elemAry no: '+elemAry.length);
	}
    }else{
        console.error('ERROR: response NOT available');
    }
    return elemAry;
};

export default function MapPage() {
    /*storage*/
    const [ary, setAry] = useState([]);
    const getData= async ()=>{
	//console.log('getData() start...');
        try {
            /*TODO handle errors: https://www.valentinog.com/blog/await-react/*/
            const res = await axios(config);
	    let elemAry=parseOsmElem(res);
	    setAry((ary) => elemAry);
        } catch (err) {
            console.error('ERROR: err.message: ' + err.message);
        }
	//console.log('getData() done.');
    };

    useEffect(()=>{
	/*do not wait the interval when component loads the first time*/
	getData();

	/*refresh data periodically*/
	const intervalCall=setInterval(()=>{
	    getData();
	}, interval);
	/*TODO adjust interval, make it available via config file*/
	return ()=>{
	    /*clean up*/
	    clearInterval(intervalCall);
	};
    },[]);
    return (
	<>
	    <Map elements={ary}/>
	</>
    );
}
