from operator import itemgetter


def parse_profiles_runs_info(text_file_name, daystr='', timesorted=True):
    """Parse text file containing flight profiles and runs times
       a.k.a. FAAM sawtooth summary.

       Args:
       -----
           test_file_name: str, file name

       Kwargs:
       -------
           daystr: str, in format '%Y%m%d' date of observations, e.g. 20130326.
                   Defaults to an empty string.
           timesorted: bool, if True, sorts the tuples time-wise

       Returns:
       --------
           list of tuples like (name, start_time, finish_time)

       Example of sawtooth summary text file:
       --------------------------------------
           Profile 1
           111420
           111822
           Profile 2
           121459
           123830
           Profile 3
           131540
           131654
    """
    with open(text_file_name) as f:
        profiles_and_runs = [i.rstrip('\n').lower() for i in f.readlines()]
    fl_profiles_i = [n for n, l in enumerate(profiles_and_runs) if l.startswith('profile')]
    fl_runs_i = [n for n, l in enumerate(profiles_and_runs) if l.startswith('run')]
    fl_profiles = [(profiles_and_runs[n], daystr+profiles_and_runs[n+1], daystr+profiles_and_runs[n+2]) for n in fl_profiles_i]
    fl_runs = [(profiles_and_runs[n], daystr+profiles_and_runs[n+1], daystr+profiles_and_runs[n+2]) for n in fl_runs_i]
    res = fl_profiles+fl_runs
    if timesorted:
        return sorted(res, key=itemgetter(2))
    else:
        return res