'use strict';

const fs = require('fs');
const path = require('path');

const config = require('../build.json');

// Change current directory to script location so that
// the relative paths of the resources can be resolved
process.chdir(path.dirname(process.argv[1]));

function createDirectory(dir) {
    fs.mkdirSync(
        dir,
        { recursive: true },
        (error) => {
            if (error !== null) {
                console.error('Error while creating directory', error);
            }
        }
    );
}

function transformData() {
    var matrix = fs.readFileSync(path.join('../', config.path.data, 'risk-ladder.tsv'), 'utf8');

    // TSV wird geparst
    matrix = matrix.split('\n').map(l => l.split('\t'));

    var rowCount = matrix.length - 1;
    var colCount = matrix[0].length;

    var result = {reasons:[], filters:[]};
    var filters = new Map();
    var basisrisiko;

    // Die einzelnen Einträge werden ausgelesen
    for (var r = 1; r < rowCount; r++) {
        result.reasons[r-1] = {
            title: matrix[r][1],
            info: matrix[r][2],
            source: matrix[r][23],
            url: matrix[r][24],
            year: matrix[r][26],
            evidence: matrix[r][25],
            referenceGroup: matrix[r][27],
            comment: matrix[r][28],
            cat: matrix[r][0]
        };
    }

    // Data expected in tsv
    var ageGroups = ['', '1-13','14-17','18-20','21-59','60+'];
    var genders = ['', 'm', 'w'];
    var offset = 5;

    for (var c = offset; c < colCount; c++) {
        var alter = undefined, geschlecht = undefined;

        if (c < genders.length * ageGroups.length + offset) {

            // gender order: neutral | male | female
            switch ((c-offset) % genders.length) {
                case 0: geschlecht = ''; break;
                case 1: geschlecht = 'm'; break;
                case 2: geschlecht = 'w'; break;
            }

            // age group changes every genders.length column
            alter = ageGroups[Math.floor((c-offset) / genders.length)];
        }

        if (alter === undefined && geschlecht === undefined) continue;
        if (alter === undefined || geschlecht === undefined) throw Error([alter, geschlecht].join('\n'));

        var key = alter + '_' + geschlecht;
        var filter = {
            alter:alter,
            geschlecht:geschlecht,
            entries:[]
        };
        result.filters.push(filter);
        if (filters.has(key)) throw Error();
        filters.set(key, true);

        for (var r = 1; r < rowCount; r++) {
            var val = parseFloat(matrix[r][c].replace(/,/g, '.'));
            var value;
            if (isNaN(val)) {
                value = 1;
            } else {
                value = val;
            }
            filter.entries[r-1] = value;
        }

        // // Risiko wird aus Basisrisiko und Faktorisierung berechnet
        if (key === '_') {
            basisrisiko = filter.entries;
        } else {
            filter.entries = filter.entries.map(function (v,i) {
                var val = v;
                if (isNaN(v)) {
                    val = 1;
                } else {
                    val = Math.round(v * basisrisiko[i] * 1e10) / 1e10;
                }
                return val;
            });
        }
    }

    fs.writeFileSync(path.join('../', config.path.output, config.path.data, 'data_de.json'), JSON.stringify(result, null, '\t'), 'utf8');
}

createDirectory(path.join('../', config.path.output, config.path.data));
transformData();
