var filesystem = require('fs');
var patients = [];

filesystem.readFile('../data/patientlist.json', 'utf8', (err, data) => {
    if (err)
        return console.log(err);

    patients = JSON.parse(data);
    console.log("Anzahl eingelesner Patienten: " + patients.length);
});

function writePatients() {
    filesystem.writeFile('../data/patientlist.json', JSON.stringify(patients), function (err) {
        if (err)
            return console.log(err);
        console.log("Anzahl geschriebener Patienten: " + patients.length);
    });
}

module.exports.readAll = function () {
    return patients;
}

module.exports.read = function (id) {
    return patients.find(function (element) {
        return (element.id == id);
    });
}

module.exports.update = function (id, patient) {
    var count = 0;
    patients = patients.map(function (element) {
        if (element.id == id) {
            count++;
            return patient;
        } else
            return element;
    });
    writePatients();
    return count;
}