import argparse
import icalendar
from urllib.request import Request, urlopen
import re
import codecs
import time

def fetch_ics(url):
    req = Request(url)
    req.add_header('User-agent', 'Mozilla/5.0 (Windows; U; Windows NT 5.1; de; rv:1.9.1.5) Gecko/20091102 Firefox/3.5.5')
    ics = urlopen(req)
    return ics.read()

def parse_ics(ics):
    items = []
    cal = icalendar.Calendar.from_ical(ics)
    for comp in cal.walk():
        if comp.name == 'VEVENT':
            event = {}
            print(comp.get('summary'))
            titre = comp.get('summary')
            if titre==None:
                titre = 'ss'
            location = comp.get('location')
            if location==None:
                location = ''
            tab_ville = location.split(", ")
            ville = tab_ville[-3]
            url = comp.get('url')
            if url==None:
                url = ''
            event['title'] = titre
            event['date'] = str(comp.get('dtstart').dt)
            event['location'] = location
            event['ville'] = ville
            event['url'] = url
            description = comp.get('description')
            if description==None:
                description = ''
            event['text'] = description
            items.append(event)
    return items

def write_hugo(path,items):
    for item in items:
        print(item);
        if item['title']!='':
            date = item['date'][0:10]
            fname = item['title']
            fname = fname.replace(' ','-')
            fname = date+'-'+re.sub('[^0-9a-zA-Z-]*','',fname)
            fpath = path+'/'+fname+'.md'
            with open(fpath,'w') as mdfile:
                mdfile.write('---\n')
                mdfile.write('title: \"'+(item['title'].replace('"',''))+'\"\n')
                mdfile.write('date_evt: \"'+item['date']+'\"\n')
                mdfile.write('location: \"'+(item['location'])+'\"\n')
                mdfile.write('ville: \"'+(item['ville'])+'\"\n')
                mdfile.write('url_info: \"'+(item['url'])+'\"\n')
                mdfile.write('---\n\n')
                mdfile.write(item['text'])

if __name__ == '__main__':
    parser = argparse.ArgumentParser(description='ics2hugo (markdown) conversion tool.')
    parser.add_argument('--url', required=True, help='url to ics calendar.')
    parser.add_argument('--path', required=True ,help='output path of markdown files.')
    args = parser.parse_args()
    ics = fetch_ics(args.url)
    items = parse_ics(ics)
    write_hugo(args.path,items)

