import csv
import json
from typing import OrderedDict


def read_tab_raw(fname, return_params=False):
    """Read .tab file from expyfun output without segmenting into trials.

    Parameters
    ----------
    fname : str
        Input filename.
    return_params : bool
        If True, return the JSON-parsed comment header.

    Returns
    -------
    data : list of tuple
        The data with each line from the tab file being a tuple in a list.
        Each tuple is of the form (``timestamp``, ``key``, ``value``).
    params : dict
        The JSON-parsed comment header. Only returned if
        ``return_params=True``.

    See Also
    --------
    read_tab
    """
    with open(fname, 'r') as f:
        csvr = csv.reader(f, delimiter='\t')
        lines = [c for c in csvr]

    # first two lines are headers
    assert len(lines[0]) == 1 and lines[0][0].startswith('# ')
    if return_params:
        params = json.loads(lines[0][0][2:], object_pairs_hook=OrderedDict)
    else:
        params = None
    assert lines[1] == ['timestamp', 'event', 'value']
    lines = lines[2:]

    times = [float(line[0]) for line in lines]
    keys = [line[1] for line in lines]
    vals = [line[2] for line in lines]
    data = list(zip(times, keys, vals))
    return (data, params) if return_params else data