// DO NOT CHANGE!
//init app with express, util, body-parser, csv2json
const express = require('express');
const app = express()
const path = require('path');
const bodyParser = require('body-parser');

//register body-parser to handle json from res / req
app.use(bodyParser.json());

//register public dir to serve static files (html, css, js)
app.use(express.static(path.join(__dirname, "public")));

// END DO NOT CHANGE!


/**************************************************************************
****************************** csv2json *********************************
**************************************************************************/

const csv = require('csvtojson');

let csvdata;

csv()
    .fromFile("world_data.csv")
    .then((jsonObj) => {
        csvdata = jsonObj;
    });


/**************************************************************************
********************** handle HTTP METHODS ***********************
**************************************************************************/


// ------------------------------ GET ------------------------------
app.get("/items", function (req, res) {
    res.send(csvdata);
});


app.get("/items/:id", function (req, res) {
    const requested_id = parseInt(req.params.id);
    let answer = "Err, No such id " + requested_id + " in database";

    for (let i = 0; i < csvdata.length; i++) {
        if (parseInt(csvdata[i].id) === requested_id) {
            answer = csvdata[i];
        }
    }

    res.send(answer);
});


app.get("/items/:id1/:id2", function (req, res) {
    const first_requested_id = parseInt(req.params.id1);
    const second_requested_id = parseInt(req.params.id2);
    let answer = "Err, Range not possible";

    if (id_exists(first_requested_id) && id_exists(second_requested_id)
        && first_requested_id < second_requested_id) {
        answer = [];
        for (let i = 0; i < csvdata.length; i++) {
            if (parseInt(csvdata[i].id) >= first_requested_id) {
                if (parseInt(csvdata[i].id) <= second_requested_id) {
                    answer.push(csvdata[i]);
                }
            }
        }
    }

    res.send(answer);
});



app.get("/properties", function (req, res) {
    res.send(Object.keys(csvdata[0]));
});

app.get("/properties/:num", function (req, res) {
    let num = parseInt(req.params.num);
    let answer = "Err, No such property available";

    keys = Object.keys(csvdata[0]);
    if (num >= 0 && num < keys.length) {
        answer = keys[num];
    }

    res.send(answer);
});



// ----------------------------- POST ------------------------------
app.post("/items", function (req, res) {
    const new_entry = req.body;

    // set id
    const last_id = parseInt(csvdata[csvdata.length - 1].id);
    new_entry["id"] = (last_id + 1).toString();

    // add entry to csvdata
    csvdata.push(new_entry);

    res.send("Added country " + new_entry.name + " to list!");
});



// ---------------------------- DELETE -----------------------------
app.delete("/items", function (req, res) {
    const name = csvdata[csvdata.length - 1].name;

    csvdata.splice(-1, 1);

    res.send("Deleted last country " + name + "!");
});

app.delete("/items/:id", function (req, res) {
    const requested_id = parseInt(req.params.id);
    let answer = "Err, No such id " + requested_id + "in database";

    for (let i = 0; i < csvdata.length; i++) {
        if (parseInt(csvdata[i].id) === requested_id) {
            csvdata.splice(i, 1);
            answer = "Item " + requested_id + " deleted successfully.";
            break;
        }
    }

    res.send(answer);
});

// DO NOT CHANGE!
// bind server to port
const server = app.listen(3000, function () {
    console.log('Example app listening at http://localhost:3000');
});




const id_exists = (id) => {
    for (let i = 0; i < csvdata.length; i++) {
        if (parseInt(csvdata[i].id) === id) {
            return true;
        }
    }
    return false;
};