#!/usr/bin/python3

import ast

FILE='../larch/apps.py'


# This script extract the Mainapps value from the larch/apps.py file and generates the desktop files.

# #             App Name,       icon,        terminal,  Script / pyshortcuts command
# MainApps = (('Larch CLI',     'larch',       True,  'larch'),
#                         ('Larch Updater', 'larch',       True,  '_ -m pip install --upgrade xraylarch'),
#                         ('Larch GUI',     'larch',       False, 'larch --wxgui'),
#                         ('XAS Viewer',    'onecone',     False, 'xas_viewer'),
#                         ('Larix',         'onecone',     False, 'larix'),
#                         ('GSE MapViewer', 'gse_xrfmap',  False, 'gse_mapviewer'),
#                         ('XRF Viewer',    'ptable',      False, 'larch_xrf'),
#                         ('XRD1D Viewer',  'larch',       False, 'larch_xrd1d') )

MainApps = None

# find the MainApps variable without importing eveythings
with open(FILE) as f:
    content = f.read()

    nodes = ast.parse(content)
    for node in ast.walk(nodes):
        if isinstance(node, ast.Assign):
            s = ast.get_source_segment(content, node)
            if 'MainApps' in s:
                ss = ast.unparse(node.value)
                MainApps = ast.literal_eval(ss)
                break

print(MainApps)

for (app_name, icon, terminal, cmd) in MainApps:
    if cmd.startswith('_'):
        continue

    # compute the desktop fiename
    filename = f"{app_name.lower().replace(' ', '-')}.desktop"
    filename = filename if 'larch-' in filename else f'larch-{filename}'
    print(filename)

    # compute the xdg categories
    categories = ['Science', 'Physics', 'Chemistry']
    if terminal:
        categories.insert(0, 'ConsoleOnly')

    # on Debian larch -> larch_cli
    if cmd == 'larch':
        cmd = 'larch_cli'
    elif cmd == 'xrd_viewer':
        cmd = 'xrdviewer'
    if cmd.startswith('larch '):
        cmd = cmd.replace('larch ', 'larch_cli ')

    # compute the desktop file content
    cs = ['[Desktop Entry]',
         f'Name={app_name}',
         'Type=Application',
         f'Comment={app_name}',
         f'Terminal={"true" if terminal else "false"}',
         f'Icon=/usr/lib/python3/dist-packages/larch/icons/{icon}.ico',
         f'Exec=/usr/bin/{cmd}',
         f"Categories={';'.join(categories)}"
         ]

    with open(filename, mode='w+') as f:
        f.write('\n'.join(cs))
