from datetime import datetime


def read_track_logs(logfile):
    """Read in progress logs from katgui and format for plotting.
       Logs are split across two lines as follows:

       Examples of file entries:
           2020-06-19 14:56:36.004Z INFO     tracking target
           2020-06-19 14:56:36.005Z INFO     target tracked for 0.0 seconds

       Observations can also be terminated as follows:
           2020-07-10 13:25:58.253Z WARNING  Session interrupted by exception (KeyboardInterrupt)

       Args:
           logfile (str): Filepath to sensor log file.

       Returns:
           times (list): List of datetime objects.
           values (list): List of sensor values.
    """
    values = []
    times = []
    with open(logfile, 'r') as f:
        for line in f:
            # The following completely dependent on this particular 
            # log format.
            if('tracking target' in line):
                # Find start time of initiating the track:
                entry = line.split(' ')
                timestring = '{} {}'.format(entry[0], entry[1][:-1])
                time = datetime.strptime(timestring, '%Y-%m-%d %H:%M:%S.%f')
                values.append('track')
                times.append(time)
                # Find the length of the track by looking at the next line:
                next_line = f.readline()
                next_entry = next_line.split(' ')
                stop_timestring = '{} {}'.format(next_entry[0], next_entry[1][:-1])
                stop_time = datetime.strptime(stop_timestring, '%Y-%m-%d %H:%M:%S.%f')
                # Now, upon stopping, set to 'unknown'?
                times.append(stop_time)
                values.append('unknown')
    return(values, times)