import asyncio
from asyncio.windows_events import NULL
import os
import threading
import signal
import sys
import time
import re
import json
from winsdk.windows.media.control import GlobalSystemMediaTransportControlsSessionManager as MediaManager

default = {
    "album_title": "",
    "artist": "",
    "album_artist": "",
    "title": "",
    "app_name": "",
    "start_time": 0,
    "end_time": 0,
    "position": 0,
    "playback_status": 0,
    "playback_type": 0,

}
track = dict(default)

async def get_media_info(validApps):
    sessions = await MediaManager.request_async()

    allSessions = sessions.get_sessions()
    for current_session in allSessions:
        if current_session:
            if validApps == current_session.source_app_user_model_id or validApps == "*":
                #print(current_session.source_app_user_model_id)
                try:
                    info = await current_session.try_get_media_properties_async()
                except:
                    # opening the app without music playing sometimes
                    # fills the box with null data, causing a crash
                    return None

                # song_attr[0] != '_' ignores system attributes
                info_dict = {song_attr: info.__getattribute__(
                    song_attr) for song_attr in dir(info) if song_attr[0] != '_'}

                # converts winrt vector to list
                info_dict['genres'] = list(info_dict['genres'])
                info_dict['app_name'] = current_session.source_app_user_model_id
                info_dict['start_time'] = current_session.get_timeline_properties().start_time.seconds
                info_dict['end_time'] = current_session.get_timeline_properties().end_time.seconds
                info_dict['position'] = current_session.get_timeline_properties().position.seconds
                info_dict['playback_type'] = current_session.get_playback_info().playback_type.value
                info_dict['playback_status'] = current_session.get_playback_info().playback_status.value
                return info_dict

    return None

def checkMusic(validApps):
    media = asyncio.run(get_media_info(validApps))
    if (media == None):
        media = dict(default)
    appName = media['app_name']
    media = {k: v for k,
            v in media.items() if k in track}
    if (media != track):
        track.update(media)
        data = json.dumps({"title": track['title'], "artist": track['artist'], "album": track['album_title'], "album_artist": track['album_artist'], "app_name": track['app_name'], "start_time": track['start_time'], "end_time": track['end_time'], "position": track['position'], "playback_type": track['playback_type'], "playback_status": track['playback_status']})
        print(data)


def main():
    checkMusic(sys.argv[1])

    # ctrl+c handler
def signal_handler(sig, frame):
    os._exit(0)

signal.signal(signal.SIGINT, signal_handler)

if __name__ == '__main__':
    main()