#!/var/www/dev/btcams2023/python_venv/bin/python3
import requests
import hashlib
import datetime
import pytz

from icalendar import Calendar, Event
STORE="/var/www/dev/btcams2023/processed"

COLORS = {
        "#0000ff":"blue",
        "#4b0082":"indigo",
        "#ffa500":"orange",
        "#ff007f":"rose",
        "ffff00":"yellow",
        "#ff00ff":"magenta",
}

STAGES = {
        'Genesis Stage': 'genesis',
        'Orange Stage': 'orange',
        'Proof-of-Work Stage': 'pow',
        'Deep Sessions - Whale Lounge': 'whale',
        'Book Signing - Store ': 'book',
}

def main():
    normalized_events = get_json('http://localhost/dev/btcams2023/processed/calendar_items_v0.json')

    # The big one:
    ical_str = create_ical(normalized_events)

    # Save it
    with open(f"{STORE}/cal_v1_tz.ics", 'w') as ical_file:
        ical_file.write( ical_str.decode() )

    # Per stage
    for stage in STAGES.keys():
        ical_str = create_ical(normalized_events, stage)
        with open(f"{STORE}/cal_v1_filter_{STAGES[stage]}.ics", 'w') as ical_file:
            ical_file.write( ical_str.decode() )



def get_json(source_url):
    resp = requests.get( source_url )
    return resp.json()


# The worker
def create_ical( normalized_events, filter_location = None ):
    cal = Calendar()

    if filter_location:
        cal_name = f'{filter_location} @ BTC AMS 2023'
    else:
        cal_name = f'BTC AMS 2023'

    cal['calname'] = cal_name
    cal['x-wr-calname'] = cal_name
    cal['name'] = cal_name

    cal_desc = 'BTC AMS 2023 calendar - Telegram: https://t.me/+iuUfYjJ3900zNTA0'
    cal['caldesc'] = cal_desc
    cal['x-wr-caldesc'] = cal_desc
    cal['description'] = cal_desc

    cal['method'] = 'PUBLISH'

    #cal['vtimezone'] = 'Europe/Amsterdam'

    cal['X-PUBLISHED-TTL'] = 'PT6H'

    cal['prodid'] = 'MarnixCal'
    cal['version'] = '2.0'

    cal['REFRESH-INTERVAL;VALUE=DURATION'] = "P1H"

    i=0
    for normalized_event in normalized_events:
        i+=1
        event = Event()

        # Time stuff
        #event['DTSTART;TZID=Europe/Amsterdam'] = to_datetime( normalized_event['start'] )
        #event['dtstamp;TZID=Europe/Amsterdam'] = to_datetime( normalized_event['start'] )

        event.add('DTSTART', to_datetime( normalized_event['start'] ))
        event.add('DTSTAMP', to_datetime( normalized_event['start'] ))
        event.add('DTEND', to_datetime( normalized_event['end'] ))
        #event['dtend'] = to_datetime( normalized_event['end'] )

        event['location'] = normalized_event['location']

        if filter_location and not normalized_event['location'] == filter_location:
            continue


        # Title
        summary = normalized_event['title']
        if normalized_event['tag']:
            tag = normalized_event['tag']
            summary += f' ({ tag })'
        event['summary'] = summary

        event['transp'] = 'TRANSPARENT'

        if not filter_location:
            event['color'] = COLORS[ normalized_event['location_color'].lower() ] 

        #event['uid'] = hashlib.md5( f"{normalized_event['title']}-{normalized_event['speakers_str']}".encode() ).hexdigest()
        event['uid'] = f'id{i}'

        if normalized_event['speakers_str']:
            event['description'] = normalized_event['speakers_str']

        cal.add_component(event)

    cal_str = cal.to_ical()
    return cal_str

def to_datetime( timestring ):
    dt =  datetime.datetime.fromisoformat( timestring )
    #dt = dt.replace(tzinfo =  pytz.timezone('Europe/Amsterdam') )

    
    #dt_str = dt.strftime("%Y%m%dT%H%M%S")
    dt_str = dt.astimezone(pytz.timezone('Europe/Amsterdam')) #.strftime("%Y%m%dT%H%M%S")

    return dt_str


# Main
if __name__ == "__main__":
   main()
