"use strict";

/* Express web server instellen */
const express = require('express');
const server = express();

const cors = require('cors');
server.use(cors());
server.options('*', cors());	// voor nu even helemaal open zetten

const LOCAL_PORT = "1234";

let dataSet = [
		{
			"merk": "BMW",
			"type": "2002 Turbo"
		},
		{
			"merk": "Maserati",
			"type": "Khamsin"
		},
		{
			"merk": "Toyota",
			"type": "Supra"
		},	
		{
			"merk": "Nissan",
			"type": "Skyline GTR"
		}
];


// STATIC FILES HOSTEN:
server.get(['/','/testpagina.html'], function(request, response) {
    console.log('Get of /');
	
	response.sendFile(__dirname + '/testpagina.html');
});

// KOPIEER BOVENSTAANDE BLOK MET ANDERE .html FILENAME INGEVULD INDIEN JE 
// ZELF WILT OEFENEN MET de FETCH API.







/* GET bericht (random) */
server.get('/random', function (request, response) {
    if (request.method == 'GET') {

        request.on('data', function (data) {
			/* We doen niets met GET data */
        });

        request.on('end', function () {
			//console.log("Uw opgegeven content-type: " + request.get('Content-type'));
			let nr = Math.round(Math.random()*(dataSet.length-1));		
			console.log('Random item: ' + dataSet[nr].merk + " " + dataSet[nr].type);
			response.send(dataSet[nr]);
        });
    }
});


/* GET bericht (alles) */
server.get('/alles', function (request, response) {
    if (request.method == 'GET') {

        request.on('data', function (data) {
			/* We doen even niets met GET data */
        });

        request.on('end', function () {
			//console.log("Uw opgegeven content-type: " + request.get('Content-type'));
			response.send(dataSet);
        });
    }
});

/* POST bericht */
server.post('/versturen', function (request, response) {
    if (request.method == 'POST') {
        var body = '';

        request.on('data', function (data) {
            body += data.toString();
			
            if (body.length > Math.pow(10,7)) // +/- 1.6 megaByte
                request.connection.destroy();
        });


        request.on('end', function () {
			body = JSON.parse(body);
			
			// Deze stap nu overbodig ivm overeenkomende naamgeving
			body = {
				"merk": body.merk,
				"type": body.type
			}
			console.log(`Onvangen data: ${JSON.stringify(body)}`);
			dataSet.push(body);
			response.send({ "Data ontvangen:": JSON.stringify(body) + " dank daarvoor!"});
        });
    }
});


/* PUT bericht */
server.put('/wijzigen', function (request, response) {
    if (request.method == 'PUT') {
        var body = '';

        request.on('data', function (data) {
            body += data.toString();
			
            if (body.length > Math.pow(10,7)) // +/- 1.6 megaByte
                request.connection.destroy();
        });

        request.on('end', function () {
			body = JSON.parse(body);
			body = {
				"merk": body.merkWijzig,
				"type": body.typeWijzig
			}
			console.log(`Onvangen data: ${JSON.stringify(body)}`);
			let index = dataSet.findIndex(e=>e.merk==body.merk);
			console.log(index);
			
			if (index>-1){
				let oud = dataSet[index].type;
				dataSet[index].type = body.type;
				response.send({ 
								"Oude waarde:": oud,
								"Nieuwe waarde": dataSet[index].type
				});
			}
			
			// else iets tussendoor fout gegaan
        });
    }
});


/* DELETE bericht */
server.delete ('/verwijderen', function (request, response) {
    response.send({ "Deze feature: ": "is nog niet geimplementeerd"});
});



/* Webserver starten */
server.listen(LOCAL_PORT, function() {
    console.log('Server started!');	
});