# Generate vulnerability csv file for testing validatevulnerability

import numpy as np
import pandas as pd
import csv

def edit_values(df, select_fields, rows, field, increment):

    for selection in rows:
        select_row = dict(zip(select_fields, selection))
        df.loc[
            (df[list(select_row)] == pd.Series(select_row)).all(axis=1),
            field
        ] += increment

    return df

if __name__ == '__main__':

    # Original, good file that bad one shall be derived from
    df = pd.read_csv('../static/vulnerability.csv')
    kwargs = {
        'index': False,
        'float_format': '%.10e',
        'quoting': csv.QUOTE_NONE
    }
    select_fields = ['vulnerability_id', 'intensity_bin_id', 'damage_bin_id']

    # Format column names
    column_names = df.columns.tolist()
    column_names = [name.strip(' "') for name in column_names]
    df.columns = column_names

    # Incorporate all issues
    df_all_issues = df.copy()
    # Out of order vulnerability ID
    select_ooo_vulnerabilityid = [[2, 16, 83]]
    df_all_issues = edit_values(
        df_all_issues,
        select_fields,
        select_ooo_vulnerabilityid,
        'vulnerability_id',
        1
    )
    # Out of order intensity bin ID
    select_ooo_intensitybinid = [[3, 121, 31]]
    df_all_issues = edit_values(
        df_all_issues,
        select_fields,
        select_ooo_intensitybinid,
        'intensity_bin_id',
        1
    )
    # Duplicate damage bin ID
    select_dupl_damagebinid = [4, 85, 61]
    select_row = dict(zip(select_fields, select_dupl_damagebinid))
    row = df_all_issues[
        (df_all_issues[list(select_row)] == pd.Series(select_row)).all(axis=1)
    ]
    row_index = row.index.values[0]
    df_all_issues = pd.concat(
        [df_all_issues.iloc[:row_index], row, df_all_issues.iloc[row_index:]]
    )
    # Total probability for vulnerability-intensity bin combination does not sum
    # to 1
    select_tot_prob = [
        [2, 1, 1],
        [3, 25, 23]
    ]
    df_all_issues = edit_values(
        df_all_issues,
        select_fields,
        select_tot_prob,
        'probability',
        0.0001
    )
    # Insert invalid data
    missing_data = [1, 2, 4]
    select_row = dict(zip(select_fields, missing_data))
    row = df_all_issues[
        (df_all_issues[list(select_row)] == pd.Series(select_row)).all(axis=1)
    ]
    row_index = row.index.values[0]
    df_all_issues.loc[row_index, 'probability'] = np.nan

    df_all_issues.to_csv('../static/vulnerability_allissues.csv', **kwargs)
