from datetime import datetime


def read_daylio(filename):
    """
    Read the daylio exported data.

    Parameters
    ----------
    filename : str
        The Daylio CSV file path.

    Returns
    -------
    daylio : tuple
        Tuple of the dates (as datetime objects) and the recorded moods
        (as a list of numbers as strings).

    """

    # Parse the Daylio output.
    columns = ['year', 'date', 'day', 'time', 'mood', 'activities', 'note']
    mood = {c: [] for c in columns}
    with open(filename, 'r') as f:
        next(f)  # skip header
        lines = f.readlines()
        for line in lines:
            line = line.strip().split(',')
            mood['year'].append(line[0])
            mood['date'].append(line[1])
            mood['day'].append(line[2])
            mood['time'].append(line[3])
            mood['mood'].append(line[4])
            mood['activities'].append(line[5])
            mood['note'].append(line[6])

    # Convert the dates to datetime objects.
    date_format = '%Y %d %B'
    daymonth = [i.split(' ') for i in mood['date']]
    dates = ['{y:04d} {d:02d} {m}'.format(y=int(i[0]), m=i[1][1], d=int(i[1][0])) for i in zip(mood['year'], daymonth)]
    dates = [datetime.strptime(i, date_format) for i in dates]

    # Convert mood to a numeric value (higher = better).
    convert = {'rad': '5',
               'good': '4',
               'meh': '3',
               'fugly': '2',
               'awful': '1'}
    for entry in convert:
        for count, m in enumerate(mood['mood']):
            if m == entry:
                mood['mood'][count] = convert[entry]

    return (dates, mood['mood'])