import sys
sys.path.insert(0, 'ics.py')

from pprint import pprint
from itertools import islice
from operator import itemgetter

from dateutil.parser import parse
# from ics import Calendar, Event
from arrow import Arrow
import requests

runi = lambda s: s.encode('cp850', errors='replace').decode('cp850')

BASE = 'https://graph.facebook.com/v2.0/'

DAYS = [
    'monday',
    'tuesday',
    'wednesday',
    'thursday',
    'friday',
    'saturday',
    'sunday'
]


def arrow_parse(t):
    return Arrow.fromdate(parse(t))


def get_posts(access_token):
    r = requests.get(
        BASE + 'posts',
        params={
            'format': 'json',
            'id': 'parkdatcurtin',
            'access_token': access_token,
            'fields': 'updated_time,message',
            'limit': 50
        }
    )

    rj = r.json()
    if not r.ok:
        pprint(rj)
        assert r.ok

    return rj['data']


def get_date_posts(access_token):
    for post in get_posts(access_token):
        if 'message' not in post:
            # odd. why does this post not have a message?
            continue

        # ignore that which has nothing to do with what we need
        lines = post['message'].splitlines()
        for idx, line in enumerate(lines):
            if line.startswith('Monday'):

                post['message'] = '\n'.join(lines[idx:])
                yield post


def parse_day(day):
    for visit in day[1:]:
        if visit[0] != '*':
            yield ('', visit)

        elif '-' not in visit:
            # invalid, probably an announcment for that day
            continue

        else:
            location, visitors = visit[1:].split(' - ', 1)

            visitors = [
                visit
                .strip()
                .replace(b'\xe2\x80\x99'.decode(), "'")
                .replace(b'\xe2\x80\x93'.decode(), '-')
                for visit in visitors.split(',')
            ]

            for visitor in visitors:
                yield (location, visitor)


def parse_week(days):
    for day in days:
        day = day.splitlines()

        day_name, date = day[0].strip().split(' ', 1)
        if day_name.lower() not in DAYS:
            continue

        yield ((
            arrow_parse(date),
            list(parse_day(day))
        ))


def get_dates(access_token):
    for update in get_date_posts(access_token):
        days = update['message'].split('\n\n')

        yield parse_week(days)


def serialize(week):
    for dates in week:
        events_in_week = []

        for day, visits in dates:
            for location, visitor in visits:
                e = Event()

                e.begin = day
                e.location = location if location else None
                e.name = visitor

                events_in_week.append(e)

        yield events_in_week


def print_raw(raw):
    lines = raw.splitlines()

    def inner(indent=0):
        while lines:
            line = lines.pop(0)

            if line.startswith('BEGIN'):
                print('\t' * indent + line)
                inner(indent+1)
            elif line.startswith('END'):
                print('\t' * (indent - 1) + line)
                return
            else:
                print('\t' * indent + line)

    return inner()


def main():
    dates = get_dates()

    day, visits = next(next(dates))
    print(day.strftime('%d/%m/%Y'))

    places = map(itemgetter(0), visits)
    just = max(map(len, places)) + 1

    print('\n'.join(
        '{} -> {}'.format(visit[0].rjust(just), visit[1])
        for visit in visits
    ))
    return

    Arrow.strftime = lambda self, format: self

    c = Calendar()
    events = serialize(dates)

    c.events = list(events)[0]  # only add the first week

    print(len(c.events))

    # for event in c.events:
    #     # print(event.begin, end=' ')
    #     event.make_all_day()
    #     # print(event.begin)

    # # import IPython
    # # IPython.embed()

    # print_raw(str(c))

    pprint(sorted(c.events))

    # # for event in c.events:
    # #     print(runi(repr(event)))
    # #     for k, v in vars(event).items():
    # #         print(k, end=' ')
    # #         print(v)
    # pprint(c.events)
    # # pprint(list(map(repr, c.events)))

    # with open('my.ics', 'w') as fh:
    #     fh.writelines(c)

    #     print('-> Stalls')
    #     for location, visitors in visits['stalls'].items():
    #         print('@', location)
    #         for visitor in visitors:
    #             try:
    #                 print('*', visitor)
    #             except UnicodeEncodeError:
    #                 print('*', visitor.encode())

    #     print('-> Misc.', ...)
    #     for dynamic_event in visits['misc']:
    #         print('->', dynamic_event)

    #     print()


if __name__ == '__main__':
    main()

@@ -1,131 +1,29 @@
-import sys%0Asys.path.insert(0, 'ics.py')%0A%0Afrom pprint import pprint%0Afrom itertools import islice%0Afrom operator import itemgetter
+from pprint import pprint
 %0A%0Afr
@@ -58,42 +58,8 @@
 rse%0A
-# from ics import Calendar, Event%0A
 from
@@ -2306,2371 +2306,4 @@
 ys)%0A
-%0A%0Adef serialize(week):%0A    for dates in week:%0A        events_in_week = %5B%5D%0A%0A        for day, visits in dates:%0A            for location, visitor in visits:%0A                e = Event()%0A%0A                e.begin = day%0A                e.location = location if location else None%0A                e.name = visitor%0A%0A                events_in_week.append(e)%0A%0A        yield events_in_week%0A%0A%0Adef print_raw(raw):%0A    lines = raw.splitlines()%0A%0A    def inner(indent=0):%0A        while lines:%0A            line = lines.pop(0)%0A%0A            if line.startswith('BEGIN'):%0A                print('%5Ct' * indent + line)%0A                inner(indent+1)%0A            elif line.startswith('END'):%0A                print('%5Ct' * (indent - 1) + line)%0A                return%0A            else:%0A                print('%5Ct' * indent + line)%0A%0A    return inner()%0A%0A%0Adef main():%0A    dates = get_dates()%0A%0A    day, visits = next(next(dates))%0A    print(day.strftime('%25d/%25m/%25Y'))%0A%0A    places = map(itemgetter(0), visits)%0A    just = max(map(len, places)) + 1%0A%0A    print('%5Cn'.join(%0A        '%7B%7D -%3E %7B%7D'.format(visit%5B0%5D.rjust(just), visit%5B1%5D)%0A        for visit in visits%0A    ))%0A    return%0A%0A    Arrow.strftime = lambda self, format: self%0A%0A    c = Calendar()%0A    events = serialize(dates)%0A%0A    c.events = list(events)%5B0%5D  # only add the first week%0A%0A    print(len(c.events))%0A%0A    # for event in c.events:%0A    #     # print(event.begin, end=' ')%0A    #     event.make_all_day()%0A    #     # print(event.begin)%0A%0A    # # import IPython%0A    # # IPython.embed()%0A%0A    # print_raw(str(c))%0A%0A    pprint(sorted(c.events))%0A%0A    # # for event in c.events:%0A    # #     print(runi(repr(event)))%0A    # #     for k, v in vars(event).items():%0A    # #         print(k, end=' ')%0A    # #         print(v)%0A    # pprint(c.events)%0A    # # pprint(list(map(repr, c.events)))%0A%0A    # with open('my.ics', 'w') as fh:%0A    #     fh.writelines(c)%0A%0A    #     print('-%3E Stalls')%0A    #     for location, visitors in visits%5B'stalls'%5D.items():%0A    #         print('@', location)%0A    #         for visitor in visitors:%0A    #             try:%0A    #                 print('*', visitor)%0A    #             except UnicodeEncodeError:%0A    #                 print('*', visitor.encode())%0A%0A    #     print('-%3E Misc.', ...)%0A    #     for dynamic_event in visits%5B'misc'%5D:%0A    #         print('-%3E', dynamic_event)%0A%0A    #     print()%0A%0A%0Aif __name__ == '__main__':%0A    main()%0A

Remove to ics code