#!/usr/bin/env python3
import argparse
import requests
from etherpad_lite import EtherpadLiteClient, EtherpadException
from lxml import etree

DEFAULT_TEXT = '<!DOCTYPE HTML><html><body><u>Questions for {TALK_NAME}</u><br><ol class=\"number\"><li>Add questions here</ol></body></html>'

def create_pad(title, api_key, url):
    c = EtherpadLiteClient(base_params={'apikey': api_key}, base_url=url)
    name = title.lower().replace('-', '').replace(' ', '-').replace(':', '').replace('&', '-').replace('/', '').replace('?', '').replace('#', '').replace('$', '').replace(',', '').replace('–', '')[0:50]
    try:
        exists = c.getHTML(padID=name)
        c.setHTML(padID=name, html=DEFAULT_TEXT.replace('{TALK_NAME}', title))
        print(f'{title},{url}/p/{name}')
    except EtherpadException as e:
        if str(e) == 'padID does not exist':
            result = c.createPad(padID=name)
            c.setHTML(padID=name, html=DEFAULT_TEXT.replace('{TALK_NAME}', title))
            print(f'{title},{url}/p/{name}')
        elif str(e) == 'padID did not match requirements':
            print(f'{name} does not match requirements')

def process_schedule(schedule, api_key, url):
    root = etree.fromstring(schedule.encode('utf8'))
    titles = [title.text for event in root.iter('event') for title in event.iter('title')]
    for title in titles:
        create_pad(title, api_key, url)

def main():
    parser = argparse.ArgumentParser()
    parser.add_argument('schedule', metavar='SCHEDULE',
                        help='The schedule to create pads for in pentabarf XML format')
    parser.add_argument('-a', '--api_key', help='The API key to use', required=True)
    parser.add_argument('-u', '--url',
                        help='The host to connect to. Defaults to http://localhost:9001',
                        default='http://localhost:9001')
    args = parser.parse_args()
    api_key = args.api_key
    url = f'{args.url}/api'

    penta_schedule = ''
    if args.schedule.startswith('https://') or args.schedule.startswith('http://'):
        r = requests.get(args.schedule)
        r.raise_for_status()
        penta_schedule = r.text
    else:
        with open(args.schedule, 'r') as fp:
            for line in fp:
                penta_schedule += line

    process_schedule(penta_schedule, api_key, url)


if __name__ == '__main__':
    main()
