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

STORE="/var/www/dev/btcams2023/processed"

colors=dict(
        blue ="#0000ff",
        magenta ="#ff00ff",
        indigo ="#4B0082",
        orange ="#ffa500",
        rose ="#FF007F",
        yellow ="FFFF00",
        )


def main():
    json_content = get_source_json_schedule('http://localhost/dev/btcams2023//source/latest.json')

    normalized_data = normalize_data( json_content )

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

def normalize_data( json_content ):
    """Gets the odd format, then formats it"""

    # create dict Variables
    data = {
        'tags': {},
        'speaker-assignments': {},
        'speakers': {},

        'track': {},
        'public-tag': {},
        'public-speaker': {},
        'public-speaker-assignment': {},
    }

    #  Get the 'helper' data
    for include in json_content['included']:
        data[include['type']][include['id']]={}
        data[include['type']][include['id']]['attributes'] = include['attributes']

        if 'relationships' in include:
            data[include['type']][include['id']]['relationships'] = include['relationships']

    # Parse speakers
    for sa_id in data['speaker-assignments']:
        # Empty object
        data['speaker-assignments'][sa_id]['speakers']=[]

        speaker_id = data['speaker-assignments'][sa_id]['relationships']['speaker']['data']['id']

        # Assign
        data['speaker-assignments'][sa_id]['speakers'].append(
                data['speakers'][speaker_id]['attributes'],
            )

        # Clear rels
        del( data['speaker-assignments'][sa_id]['relationships'] )

        
        
    
    # Store helper jsons
    with open(f"{STORE}/speakers.json", 'w') as speakers_file:
        speakers_file.write( json.dumps( data['public-speaker'] ) )
    with open(f"{STORE}/speaker-assignments.json", 'w') as speaker_assignments_file:
        speaker_assignments_file.write( json.dumps( data['public-speaker-assignment'] ) )
    with open(f"{STORE}/tags.json", 'w') as tags_file:
        tags_file.write( json.dumps( data['public-tag'] ) )
    with open(f"{STORE}/tracks.json", 'w') as tags_file:
        tags_file.write( json.dumps( data['track'] ) )


    # Store where?
    calendar_items_v0 = []

    # Go through actual data
    for datum in json_content['data']:
        # Hope we just get time slots here
        assert( datum['type'] == "public-timeslot")

        title = datum['attributes']['title']
    
        if not title or not len(title):
            # Weird empty ones...
            continue

        start = datetime.datetime.fromisoformat( datum['attributes']['start-time'] )
        end = datetime.datetime.fromisoformat( datum['attributes']['end-time'] )

        # Get location
        #location = data['tags'][datum_location['id']]['attributes']
        track_id = datum['relationships']['track']['data']['id']
        try:
            location = data['track'][track_id]['attributes']
        except:
            raise


        # Speakers
        speakers_strs = []
        for datum_speaker_assignments in datum['relationships']['speaker-assignments']['data']:
            sa_id = datum_speaker_assignments['id']

            # Find actualspeakers
            actual_speaker_id = data['public-speaker-assignment'][sa_id]['relationships']['speaker']['data']['id']
            
            try:
                speaker_obj = data['public-speaker'][actual_speaker_id]['attributes']
            except KeyError:
                continue

            speakers_strs.append( format_speaker_string( speaker_obj ) )
        speakers_str = '\n'.join(speakers_strs)

        # Tags
        try:
            tag_id = datum['relationships']['tags']['data'][0]['id']
        except:
            tag_id = None
            tag = ""

        if tag_id:
            tag = data['public-tag'][tag_id]['attributes']['name']
            

        calendar_items_v0.append(dict(
                    title = nuller(title),
                    start = start.isoformat(),
                    end = end.isoformat(),
                    speakers_str = nuller(speakers_str),
                    location = location['name'],
                    location_color = colors[location['color']],
                    tag = nuller(tag),
                    ))

    # Gone through all
    with open(f"{STORE}/calendar_items_v0.json", 'w') as calendar_items_v0_file:
        calendar_items_v0_file.write( json.dumps( calendar_items_v0 ) )
        


def format_speaker_string( speaker_object ):
    #print(speaker_object)
    # Build a string
    return_value = ""
    
    if 'first-name' in speaker_object and speaker_object['first-name']:
        return_value += speaker_object['first-name'] + " "

    if 'middle-name' in speaker_object and speaker_object['middle-name']:
        return_value += speaker_object['middle-name'] + " "

    if 'last-name' in speaker_object and speaker_object['last-name']:
        return_value += speaker_object['last-name']

    if 'company-name' in speaker_object and speaker_object['company-name']:
        if 'job-title' in speaker_object and speaker_object['job-title']:
            return_value += " (" + speaker_object['job-title'] + " @ " + speaker_object['company-name']  + ")"
        else:
            return_value += " (" + "NOJOBTITLE" + " @ " + speaker_object['company-name']  + ")"

    return return_value

def nuller(input_str):
    if not input_str or not len(input_str):
        return None
    return input_str


if __name__ == "__main__":
   main()
