const express = require('express');
const turf = require('@turf/turf');
const fs = require('fs');
const bodyParser = require('body-parser');
const cors = require('cors');
const pino = require('express-pino-logger')();
var fileName = "public/locations.json";
let file = require("../public/locations");
let geojson = "public/denver_neighborhoods.geojson";

const app = express();
app.use(bodyParser.urlencoded({extended: false}));
app.use(bodyParser.json());
app.use(pino);
app.use(cors({
    origin: 'http://localhost:3000'
}));

const loadMap = () => {
    fs.readFile(geojson, function (err, geosonData) {
        let geosonParsed = JSON.parse(geosonData);
        //set the reports to zero to rebuild...
        for(let y = 0; y < geosonParsed.features.length; y++) {
            geosonParsed.features[y].properties.reports = 0;
        }
        fs.readFile(fileName, function (err, locationData) {
            let locationParsed = JSON.parse(locationData);
            for (let x = 0; x < locationParsed.length; x++) {
                let coords = [locationParsed[x].lng, locationParsed[x].lat];
                let pt = {
                    "type": "Feature",
                    "properties": {
                        "marker-color": "#0f0"
                    },
                    "geometry": {
                        "type": "Point",
                        "coordinates": coords
                    }
                };
                for (let i = 0; i < geosonParsed.features.length; i++) {
                    let neighborhood = geosonParsed.features[i];
                    let isInside = turf.inside(pt, neighborhood);
                    if (isInside) {
                        if (geosonParsed.features[i].properties.reports > 0) {
                            geosonParsed.features[i].properties.reports++;
                        } else {
                            geosonParsed.features[i].properties.reports = 1;
                        }
                    }
                }
            }
            fs.writeFile(geojson, JSON.stringify(geosonParsed), function (err) {
                if (err) return console.log(err);
                console.log('written to:  ' + geojson);
            });
        });
    });
};

const addToMap = (lat, lng) => {
    fs.readFile(geojson, function (err, geosonData) {
        let geosonParsed = JSON.parse(geosonData);
        let coords = [lng, lat];
        let pt = {
            "type": "Feature",
            "properties": {
                "marker-color": "#0f0"
            },
            "geometry": {
                "type": "Point",
                "coordinates": coords
            }
        };
        for (let i = 0; i < geosonParsed.features.length; i++) {
            let neighborhood = geosonParsed.features[i];
            let isInside = turf.inside(pt, neighborhood);
            if (isInside) {
                if (geosonParsed.features[i].properties.reports > 0) {
                    geosonParsed.features[i].properties.reports++;
                } else {
                    geosonParsed.features[i].properties.reports = 1;
                }
            }
        }

        fs.writeFile(geojson, JSON.stringify(geosonParsed), function (err) {
            if (err) return console.log(err);
            console.log('written to:  ' + geojson);
        });
    });
};

app.listen(3001, () => {
        console.log('Express server is running on localhost:3001');
    console.log(process.cwd() + fileName);
    loadMap();
    }
);

app.get('/loadMap', (req, res) => {
    fs.readFile(fileName, function (err, data) {
        let json = JSON.parse(data);
        res.send(json);
    });
});

app.post('/report/submit', (req, res) => {
    console.log(req.body);
    let coords = {lat: req.body.lat, lng:req.body.lng};
    fs.readFile(fileName, function (err, data) {
        let json = JSON.parse(data);
        json.push(coords);
        fs.writeFile( fileName, JSON.stringify(json), function (err) {
            if (err) return console.log(err);
            console.log('written to:  ' + fileName);
        });
    });
    console.log("A report has been posted!");
    addToMap(req.body.lat, req.body.lng);
});