let geomFC = ""; // list of geometries FC
let linkFC = ""; // tous les link avaec les ref nonref
let FCLevel = "";

let TheLinks = []; // reconstruction de ce qui nous interesse

function pdeGeomFC(level) {
    console.log("pdeGeomFC " + level);
    FCLevel = level;

    let layers = {
        ROAD_GEOM_FC: {
            callback: pdeGotRoadGeomFC,
            fcLayers: [level]
        },
        LINK_ATTRIBUTE_FC: {
            callback: pdeGotLinkAttribFC,
            fcLayers: [level]
        } // en dernier pour avoir la geometrie, et le direction of Travel
    };

    geomFC = [];
    linkattrib = [];

    pdeManager.setLayers(layers);
    let bb = hm.getViewBB();
    pdeManager.setBoundingBox(bb);
    pdeManager.run().then(res => {
        pdeGeomFinished(res);
    })

    let rects = pdeManager.getTilesInfo();
    console.log(rects);

    rects.forEach(rect => {
        console.log(rect.bb);
        hm.polyline({
            layer: "tiles",
            coords: hm.bb2Poly(rect.bb),
            style: {
                lineWidth: 2,
                strokeColor: "rgba(100, 100, 0, 0.5)",
            }
        });
    });


} //of pdeGeomFC


function pdeGotRoadGeomFC(resp) {
    //var name = "pdeGotRoadGeomFC";
    //_HM.log(name+" Meta: ",resp.Meta);
    console.log("pdeGotRoadGeomFC rows0", resp.Rows[0]);

    for (let i = 0; i < resp.Rows.length; i++) {
        geomFC.push(resp.Rows[i]);


        TheLinks[resp.Rows[i].LINK_ID] = {
            lat: resp.Rows[i].LAT,
            lng: resp.Rows[i].LON,
            name: resp.Rows[i].NAME

        };
    }
}


// only to get sens of travel
function pdeGotLinkAttribFC(resp) {
    console.log("pdeGotLinkAttribFC rows0", resp.Rows[0]);
    for (var i = 0; i < resp.Rows.length; i++)
        linkattrib.push(resp.Rows[i]);
}


// here, one can combine the right bits and pieces which are of interest
function pdeGeomFinished(nrTilesRequested) {
    console.log("pdeGeomFinished");
    infoClean();
    infoAdd("FC" + FCLevel);
    infoAdd(nrTilesRequested + " Tiles and " + geomFC.length + " geometries");
    infoAdd(linkattrib.length + " links");

    // combine whatever of interestfrom LinkATTRIB
    for (var i = 0; i < linkattrib.length; i++) {
        var obj = TheLinks[linkattrib[i].LINK_ID];
        if (!obj)
            continue;
        obj.TRAVEL_DIRECTION = linkattrib[i].TRAVEL_DIRECTION;
        obj.SPEED_CATEGORY = linkattrib[i].SPEED_CATEGORY;
    }

    var color;
    switch (FCLevel) {
        case 1:
            color = 'rgba(0, 128, 255, 0.7)';
            break;
        case 2:
            color = 'rgba(140, 90, 125, 0.7)';
            break;
        case 3:
            color = 'rgba(220, 00, 220, 0.7)';
            break;
        case 4:
            color = 'rgba(0, 228, 0, 0.7)';
            break;
        case 5:
            color = 'rgba(40, 60, 80, 0.7)';
            break;
    }

    var style = {
        lineWidth: 4,
        strokeColor: color
    }

    for (let i = 0; i < geomFC.length; i++) {
        //let coords = hm.coordsPDE2Array(geomFC[i].LAT, geomFC[i].LON);

        hm.polyline({
            coordsPDE: geomFC[i],
            data: JSON.stringify(geomFC[i]),
            layer: "roads",
            style: style,
            pointerEnter: function (target, coord, event) {
                console.log(target.getData());
            }
        });
    }
}

function GEOMGetFeatures() {
    var features = [];

    for (linkid in TheLinks) {

        let link = TheLinks[linkid];

        var properties = {
            linkId: linkid
        };

        if (typeof link.name != "undefined" && link.name) properties.NAME = link.name;
        properties.SPEED_CATEGORY = link.SPEED_CATEGORY;

        features.push({
            type: "Feature",
            geometry: {
                type: "LineString",
                coordinates: hm.coordsPDE2Array(link.lng, link.lat)
            },
            properties: properties
        });
    }

    return features;
}


// from coord, find country then call cityTiles
async function rgc(coord) {
    let res = await hm.reverseGeocode(coord);
    console.log(res);
    console.log(res.address.Country);
    countryLevel(res.address.Label);
}



async function countryLevel(country) {
    console.log("cityTiles");

    hm.layerEmpty("tiles");

    let layers = {
        DUMMY: {
            level: -1
        }
    };

    pdeManager.setLayers(layers);
    let res = await hm.geocode(country, {
        additionaldata: "IncludeShapeLevel,country"
    });
    center = res.coord;
    hm.setCenter(center);

    _country = res.body.Response.View[0].Result[0].Location.Address.Country.toLowerCase();
    console.log("country", _country);

    let shape = "";
    try {
        shape = res.body.Response.View[0].Result[0].Location.Shape.Value;
    } catch (e) {
        console.log(e);
        console.log(res.body.Response.View[0].Result[0].Location);
    }
    //console.log("shape", shape);

    let geojson = hm.WKTparse(shape);
    console.log("geojson length", geojson.coordinates.length)
    console.log("geojson ", geojson);

    let poly = [];
    // find all tiles doing a border of a polygon
    geojson.coordinates.forEach((coords, i) => {
        //       if (i != 12) return; //12 is Corsica 

        let outer = (geojson.type == "MultiPolygon") ? coords[0] : coords;
        //console.log("outer length", outer.length)
        //console.log("outer ", outer)

        outer.forEach((coord, j) => {
            const [x, y] = coord;
            outer[j][0] = y;
            outer[j][1] = x;
        });
        hm.polyline({
            layer: "tiles",
            coords: outer,
            style: {
                lineWidth: 2,
                strokeColor: "red",
            }
        });
        poly.push(outer);

    });

    const _timer = new Date().getTime();

    pdeManager.setBoundingPolys(poly);

    let delta = new Date().getTime() - _timer;
    console.log("computation time", delta);
    let rects = pdeManager.getTilesInfo();
    console.log("Number of tiles", rects.length);
    const rps = 20;
    let secs = rects.length / rps;
    let hours = Math.floor(secs / 3600);
    secs -= hours * 3600;
    let min = Math.floor(secs / 60);
    secs -= min * 60;
    secs = Math.floor(secs);
    console.log(`duration @rps ${rps}:  ${hours}:${min}:${secs}`)
    
    rects.forEach(rect => {
        let coords = hm.bb2Poly(rect.bb);

        hm.polyline({
            layer: "tiles",
            coords: coords,
            style: {
                lineWidth: 2,
                strokeColor: "rgba(100, 100, 0, 0.5)",
            }
        });

    });



} //of pdeGeomFC