import React, { useState } from 'react';
import axios from 'axios';
import Pbf from 'pbf';
import Hello from '../components/hello';
import { FeedMessage } from '../../proto2js/js/gtfs-rt.js';
import Map from '../components/map/map';
import '../style.css';
/**/
function insertCharToString(str,indexPos,char){
  return str.substring(0, indexPos) + char + str.substring(indexPos);
};
const Home = () => {
    /*storage*/
    const [vehPos, setVehPos] = useState([]);
    /*fetch vehPost in a JavaScript function*/
    const getVehPos = async () => {
        try {
            /*TODO handle errors: https://www.valentinog.com/blog/await-react/*/
            let url = 'https://soll.vbn.de/vehicle-positions';
            //let url = 'http://localhost:8080/vehicle-positions';
            const res = await axios.get(url,
					{
					    responseType: 'arraybuffer'
					    //responseType: 'blob'
					});
	    //TODO remove debugging
            if (res.data) {
                //console.log('getVehPos() JSON res: ', JSON.stringify(res));
                //console.log('getVehPos() res.data: ', res.data);
		const pbf = new Pbf(res.data);
                //console.log('getVehPos() JSON pbf: ', JSON.stringify(pbf));
		const feed = FeedMessage.read(pbf);
		if (feed.header) {
		    //console.log('getVehPos() header available');
		    const {gtfs_realtime_version, incrementality, timestamp}=feed.header;
		    if(gtfs_realtime_version && incrementality, timestamp){
			console.log(`getVehPos() gtfs_realtime_version: ${gtfs_realtime_version}, incrementaltiy: ${incrementality}, timestamp: ${timestamp} available`);
		    }
		}else{
		    console.error('getVehPos() header NOT available');
		}
		const messages = [];
                //console.log('getVehPos() feed: ', feed);
                //console.log('getVehPos() JSON feed: ', JSON.stringify(feed));
		feed.entity.forEach(entity => {
		    const vehiclePos = entity.vehicle;
		    if (vehiclePos) {
			//console.log('getVehPos() vehiclePos available');
			const { trip, position, vehicle } = vehiclePos;
			if (trip && position && vehicle) {
			    const {trip_id, route_id, direction_id, start_time, start_date, schedule_relationship}=trip;
			    if(trip_id){
				console.log(`getVehPos() trip_id:${trip_id} available`);
			    }else{
				console.log(`getVehPos() trip_id NOT available`);
			    }
			    if(route_id){
				console.log(`getVehPos() route_id:${route_id} available`);
			    }else{
				console.log(`getVehPos() route_id NOT available`);
			    }
			    if(direction_id){
				console.log(`getVehPos() direction_id:${direction_id} available`);
			    }else{
				console.log(`getVehPos() direction_id NOT available`);
			    }
			    const {latitude, longitude, bearing, odometer, speed}=position;
			    if(latitude){
				console.log(`getVehPos() latitude:${latitude} available`);
			    }
			    if(longitude){
				console.log(`getVehPos() longitude:${longitude} available`);
			    }
			    //remove tailing dot
			    //match a dot when it is followed by a whitespace or the end of the string
			    /*A function to trim trailing dots*/
			    /*TODO Is this precaution required?*/
			    let latFormed = latitude.toString().replace(/\.+$/, "");
			    //let latFormed = trimTrailingChars(latitude.toString(), '\.');
			    //console.log(`getVehPos() latFormed:${latFormed}`);
			    latFormed=insertCharToString(latFormed,latFormed.length - 7,'.');
			    console.log(`getVehPos() latFormed:${latFormed}`);
			    let lonFormed = longitude.toString().replace(/\.+$/, "");
			    lonFormed=insertCharToString(lonFormed,lonFormed.length - 7,'.');
			    console.log(`getVehPos() lonFormed:${lonFormed}`);
			    const message={
				routeId: route_id === undefined ? -1 : parseInt(route_id,10) || -2,
				lat: latFormed === undefined ? -360 : latFormed,
				lon: lonFormed === undefined ? -720 : lonFormed,
			    };
		            messages.push(message);
			} else {
			    console.error('getVehPos() trip, position & vehicle NOT unavailable ');
			}
		    } else {
			console.error('getVehPos() vehiclePos NOT available');
		    }
		});
		/*set state*/
		setVehPos(messages);
            } else {
                console.error('getVehPos() res.data unavailable ');
            }
        } catch (err) {
            console.error('err.message: ' + err.message);
        }
    };

    return (
	<>
	    <h2>Home</h2>
	    <h3>(React.js Lambda Function Component)</h3>
	    <Hello msg="Hello World!" />
            <button onClick={getVehPos}>getVehPos</button>
	    <p>
		vehicle position count: {vehPos.length}
	    </p>
	    <Map vehPos={vehPos}/>
	</>
    );
}

export default Home
