import csv
import io


def read_model_analysis_csv(csvfile):
    """
    Reads CSV generated from a spreadsheet of the same form as 'EXAMPLE template results spreadsheet v2 warming levels'.
    Returns the model analyses as a list of Dicts.
    """

    # List of keys corresponding to the column headings for v2 of the template
    keys = ['dataset', 'n_members', 'experiment', 'statmodel', 'seasonalcycle', 'spatialpattern', 'sigma', 'sigma_min', 'sigma_max', 'xi', 'xi_min', 'xi_max', 'statprop', 'conclusion', 'include_model', 'threshold10y', 'GMSTnow',  'PR', 'PR_min', 'PR_max', 'Delta_I', 'Delta_I_min', 'Delta_I_max', 'GMSTfuture', 'PR_future', 'PR_min_future', 'PR_max_future', 'Delta_I_future', 'Delta_I_min_future', 'Delta_I_max_future']

    # CSV uploaded as bytes - assume UTF-8 encoding
    csv_reader = csv.reader(io.StringIO(csvfile.read().decode('utf-8')))

    rows = []
    parse_rows = False
    for values in csv_reader:

        if parse_rows:
            # Zip up the values in the row with the keys for each column heading
            params = {k:v for k,v in zip(keys,values)}

            # If the 'Include model?' field is empty (or just whitespace) then assume we have reached the end of the input rows
            if not params['include_model'] or params['include_model'].isspace():
                print('Log: Found row with empty "Include model?" field. Stopping CSV parsing.')
                break

            rows.append(params)
        else:
            # Skip rows until 'Model' heading appears in first column.
            # Once found, skip the following line (that contains a description
            # of the column) and begin parsing rows.
            if values[0] == 'Model':
                next(csv_reader, None)
                parse_rows = True
                continue
            else:
                continue

    return rows