"""Function to parse data file generated by the plate reader."""

from pathlib import Path

import pandas as pd

import omniplate.omerrors as errors
from omniplate.parse_sunrise import parse_sunrise
from omniplate.parse_tecan import parse_tecan


def parse_plate(
    plate_reader_file,
    plate_reader_type,
    data_dir_path=".",
    sheet_number=0,
    export=False,
):
    """
    Parse plate-reader output into a long dataframe.

    Note that the plate-reader file is assumed to be an Excel file
    and that time is converted into hours.

    Parameters
    ----------
    plate_reader_file: str
        The name of the data file created by a platereader.
    plate_reader_type: str
        The type of plate reader, currently only "Tecan"
        for a Tecan M200 or Tecan F200.
    data_dir_path: str, optional
        The path to the plate_reader_file.
    sheet_number: integer, optional
        The sheet to read from an excel file.
    export: boolean, optional
        If True, write parsed data to tsv file.

    Example
    -------
    >>> from om_code.parse_plate import parse_plate
    >>> rdf= parse_plate("ExampleData.xlsx", "Tecan", datadirpath="data")
    >>> print(rdf)

                time well      OD   GFP  AutoFL  mCherry
    0       0.000000   A1  0.2555  46.0    18.0     19.0
    1       0.232306   A1  0.2725  45.0    17.0     17.0

    """
    if isinstance(data_dir_path, str):
        data_dir_path = Path(data_dir_path)
    if plate_reader_type == "tidy":
        print(
            "Columns must be labelled 'time', 'well', 'OD', etc., "
            "and time must be in units of hours."
        )
        try:
            if ".tsv" in plate_reader_file:
                rdf = pd.read_csv(
                    str(data_dir_path / plate_reader_file), sep="\t", index_col=0
                )
            else:
                rdf = pd.read_csv(
                    str(data_dir_path / plate_reader_file), index_col=0
                )
        except FileNotFoundError:
            raise errors.FileNotFound(str(data_dir_path / plate_reader_file))
        if rdf.time.max() > 100:
            print("Warning: time does not appear to be in hours.")
        return rdf
    else:
        # load data
        try:
            dfd = pd.read_excel(
                str(data_dir_path / plate_reader_file), sheet_name=sheet_number
            )
        except FileNotFoundError:
            raise errors.FileNotFound(str(data_dir_path / plate_reader_file))
        # create a dict to store data
        rdict = {"time": [], "well": []}
        # parse loaded data frame
        if plate_reader_type == "Tecan":
            rdict = parse_tecan(dfd, rdict)
        elif plate_reader_type == "Sunrise":
            rdict = parse_sunrise(dfd, rdict)
        else:
            raise ValueError(f"{plate_reader_type} not recognised.")
        # convert parsed dict to data frame
        rdf = pd.DataFrame.from_dict(rdict)
        if export:
            outname = plate_reader_file.split(".")[0] + ".tsv"
            print(f"exporting {outname}")
            rdf.to_csv(str(data_dir_path / outname), sep="\t")
        return rdf
