import sys
from Mariadb import Mariadb

if len(sys.argv) < 2:
    print("Usage is:\python3 importCSV.py <filename.csv>")
    sys.exit(1)

db = Mariadb(configFile='config.yml')

f_id = db.checkActiveFlight()
print("Using flight ID: ", f_id)

def get_avg(a, b, c):
    ''' Takes three string floats, returns a string float average '''
    return ( float(a)+float(b)+float(c) ) / 3.0

def insertBeelineGPS(file_handler, f_id):
    print("hit insertBeelineGPS")

def insertRocketAvionics(file_handler, f_id):
    ''' Insert a CSV file generated by the rocket avionics '''
    print("hit insertRocketAvionics")

    partCols = "f_id, s_id, time, "        \
               "gyro_x, gyro_y, gyro_z, "  \
               "acc_x, acc_y, acc_z, "     \
               "temp, alt"

    return insertCSVRows(
        file_handler, "Rocket_Avionics", f_id, "None", partCols
    )

def insertOther(file_handler, f_id):
    print("hit insertOther")

def insertPayloadAvionics(file_handler, f_id):
    ''' Insert a CSV file generated by the payload avionics '''
    print("hit insertPayloadAvionics")

    fullCols = "f_id, s_id, time, "        \
               "gyro_x, gyro_y, gyro_z, "  \
               "acc_x, acc_y, acc_z, "     \
               "temp, alt, "        \
               "prop_pid, prop_pwm, "      \
               "counter_pid, counter_pwm"

    partCols = "f_id, s_id, time, "        \
               "gyro_x, gyro_y, gyro_z, "  \
               "acc_x, acc_y, acc_z, "     \
               "temp, alt"

    return insertCSVRows(
        file_handler, "Payload_Avionics", f_id, fullCols, partCols
    )


def insertCSVRows(file_handler, table, f_id, fullCols, partCols):
    ''' Insert rows from a CSV file using the appropriate headers '''
    fullData = []
    partData = []
    rowsAdded = 0
    rowsError = 0

    fullLength = len(fullCols.split(','))
    partLength = len(partCols.split(','))

    for line in file_handler:
        fields = [str(f_id)]+line[:-1].split(',')
        length = len(fields)

        if length == 23 and fields[0] != 'state':
            f_id, s_id, time = fields[0:3]
            s_id = int(s_id)+1
            time = 'FROM_UNIXTIME({})'.format(time)
            gyro_x = get_avg(fields[3], fields[9],  fields[15])
            gyro_y = get_avg(fields[4], fields[10], fields[16])
            gyro_z = get_avg(fields[5], fields[11], fields[17])
            acc_x  = get_avg(fields[6], fields[12],  fields[18])
            acc_y  = get_avg(fields[7], fields[13],  fields[19])
            acc_z  = get_avg(fields[8], fields[14],  fields[20])
            temp, alt = fields[21:]
            data = [f_id, s_id, time, gyro_x, gyro_y, gyro_z,
                    acc_x, acc_y, acc_z, temp, alt]

            db.insertRow( table, partCols, data )
            rowsAdded += 1

        elif length == fullLength and fields[0] != 'state':
            f_id, s_id, time = fields[0:3]
            s_id = int(s_id)+1
            time = 'FROM_UNIXTIME({})'.format(time)
            gyro_x = get_avg(fields[3], fields[9],  fields[15])
            gyro_y = get_avg(fields[4], fields[10], fields[16])
            gyro_z = get_avg(fields[5], fields[11], fields[17])
            acc_x  = get_avg(fields[6], fields[12],  fields[18])
            acc_y  = get_avg(fields[7], fields[13],  fields[19])
            acc_z  = get_avg(fields[8], fields[14],  fields[20])
            temp, alt, ppid, ppwm, cpid, cpwm = fields[21:]
            data = [f_id, s_id, time, gyro_x, gyro_y, gyro_z,
                    acc_x, acc_y, acc_z, temp, alt, ppid, ppwm, cpid, cpwm]

            db.insertRow( table, partCols, data )
            rowsAdded += 1
        else:
            print("Err on length: ", line)
            rowsError += 1

    return rowsAdded, rowsError

filename = sys.argv[1]
with open(filename, 'r') as csvfile:
    # Check the file header to see what the source is:
    insertType = {
        'BeelineGPS\n'      :   insertBeelineGPS,
        'av_rocket.csv'     :   insertRocketAvionics,
        'av_payload.csv'    :   insertPayloadAvionics,
    }.get(filename, insertOther)
    # Skip the csv header
    next(csvfile)
    rowsAdded, rowsError = insertType(csvfile, f_id)
    print("Finished importing {}.".format(filename))
    print("Added {} new rows with {} errors.".format(rowsAdded, rowsError))
