import pandas as pd
import time
import re

# par défaut la coommande speedtest au format csv ne donne pas de timpestamp
# ajout d'une colonne timestamp au fichier csv existant
time = time.strftime('%d-%m-%Y:%H:%M:%S')

from csv import writer
from csv import reader

# création de la fonction ajout de la colonne date dans le fichier existant
def add_column_in_csv(input_file, output_file, transform_row):
    """ Append a column in existing csv using csv.reader / csv.writer classes"""
    # Open the input_file in read mode and output_file in write mode
    with open(input_file, 'r') as read_obj, \
            open(output_file, 'w', newline='') as write_obj:
        # Create a csv.reader object from the input file object
        csv_reader = reader(read_obj)
        # Create a csv.writer object from the output file object
        csv_writer = writer(write_obj)
        # Read each row of the input csv file as list
        for row in csv_reader:
            # Pass the list / row in the transform function to add column text for this row
            transform_row(row, csv_reader.line_num)
            # Write the updated row / list to the output file
            csv_writer.writerow(row)
# appel de la fonction ajout de colonne et écriture de fichier avec la nouvelle colonne date
add_column_in_csv('/var/tmp/debit.csv', '/var/tmp/debitwithdate.csv', lambda row, line_num: row.append(time))

# lecture du nouveau fichier csv
df = pd.read_csv('/var/tmp/debitwithdate.csv',names=["ServerName","ServerID","Latency","Jitter","PacketLoss","Download",
"Upload","DoDataLoad","UpDataLoad","ResultURL","Date"])

# conversion en Mbps et arrondi à deux chiffres après la virgule
df['Download'] /= 125000 # same as df['Download'] = df['Download'] / 125000
df['Upload'] /= 125000 # same as df['Upload'] = df['Upload'] / 125000
decimals = 2
df['Upload'] = df['Upload'].apply(lambda x: round(x, decimals))
df['Download'] = df['Download'].apply(lambda x: round(x, decimals))
df['Latency'] = df['Latency'].apply(lambda x: round(x, decimals))
df['Jitter'] = df['Jitter'].apply(lambda x: round(x, decimals))

# Ecriture du nouveau fichier dans le répertoire partagé du Syno
df.to_csv("/media/synojoker/Fibre/debitknet.csv", mode='a', header=None)