"""Function to parse data file generated by a Tecan fluorescence plate reader."""

import numpy as np


def parseTecan(dfd, rdict):
    """Parse a data frame from a Tecan plate reader into a dict."""
    # extract datatypes
    datatypes = (
        dfd[dfd.columns[0]]
        .iloc[
            np.nonzero(
                dfd[dfd.columns[0]]
                .str.startswith("Cycle Nr", na=False)
                .to_numpy()
            )[0]
            - 1
        ]
        .to_numpy()
    )
    # if only OD data measured
    if not isinstance(datatypes[0], str):
        datatypes = ["OD"]
    # add datatypes to rdict
    for datatype in datatypes:
        rdict[datatype] = []
    # extract times of measurements
    t = (
        dfd.loc[
            dfd[dfd.columns[0]].str.startswith("Time [s]", na=False),
            dfd.columns[1] :,
        ]
        .dropna(axis="columns")
        .astype("float")
        .mean()
        .to_numpy()
        / 3600.0
    )
    # deal with overflows
    df = dfd.replace(to_replace="OVER", value=np.nan)
    cols = df.columns
    # extract data and add to rdict
    df.index = df[cols[0]]
    for x in np.arange(1, 13):
        for y in "ABCDEFGH":
            well = y + str(x)
            if well in df.index:
                data = df.loc[well, cols[1] :].to_numpy(dtype="float")
                if data.ndim == 1:
                    data = data[None, :]
                for i, tv in enumerate(t):
                    rdict["time"].append(tv)
                    rdict["well"].append(well)
                    for k, datatype in enumerate(datatypes):
                        rdict[datatype].append(data[k, i])
    return rdict
