#!/usr/bin/env python3

''' Create the lirc Supported Devices Table using data in hardware.yaml '''

import glob
import os
import sys
import yaml



MENUS = {'home_brew': 'Home-brew serial and parallel devices',
         'irda': 'IRDA/Cir hardware',
         'other': 'Other (MIDI, Bluetooth, udp, etc.)',
         'other_serial': 'Other serial port devices',
         'pda': 'PDAs',
         'soundcard': 'Home-brew (soundcard input)',
         'tv_card': 'TV cards',
         'usb': 'USB devices'
}


_TEMPLATE = '''
<table border="1">
    <tr>
        <th>Hardware</th>
        <th>Required LIRC kernel modules</th>
        <th>lircd driver</th>
        <th>Default lircd and lircmd config files</th>
        <th>Supported remotes</th>
   </tr>"
@TABLE_ROWS@
</table>
'''


def here(path):
    ' Return path added to current dir for __file__. '
    return os.path.join(os.path.dirname(os.path.abspath(__file__)), path)


def load_configs(configdir_arg):
    ''' Load config files into a dict keyed by id. '''
    configs = {}

    if configdir_arg:
        configdir = configdir_arg
    elif os.path.exists(here('configs')):
        configdir = here('configs')
    elif os.path.exists(here('../configs')):
        configdir = here('../configs')
    else:
        print("Cannot find the configuration files")
        sys.exit(1)
    configs = {}
    for path in glob.glob(configdir + '/*.conf'):
        if path == 'configuration.conf':
            continue
        with open(path) as f:
            cf = yaml.load(f.read())
        configs[cf['config']['id']] = cf['config']
    return configs


def _add_submenu(menu, configs):
    ''' Return all entries for a submenu as a string of html table rows. '''

    def getit(remote, what, _default='&nbsp;'):
        ''' Get an item from  a remote, using default if not existing. '''
        try:
            return remote[what]
        except KeyError:
            return _default

    s = '<tr><th colspan="5"><a name="%s">\n'  %  menu
    s += MENUS[menu] + '</a></th></tr> \n'
    if not configs:
        return ""
    for remote in sorted(configs, key=lambda r: getit(r, 'label', '')):
        s += '<tr>'
        s += '<td>' +  getit(remote, 'label') + '</td>'
        s += '<td>' + ' '.join(getit(remote, 'modules', ['&nbsp;'])) + '</td>'
        s += '<td>' + getit(remote, 'driver') + '</td>'
        s += '<td>'
        files = getit(remote, 'lircd_conf') + ' ' + getit(remote, 'lircmd_conf')
        s += files.replace('run_select_any_config', '')
        s += '</td>'
        s += '<td>' + getit(remote, 'supports') + '</td>'
    return s.replace('& ', '&amp; ')


def main():
    if len(sys.argv) == 2:
        configdir = sys.argv[1]
    elif len(sys.argv) == 1:
        configdir = None
    else:
        print("Usage: data2hwdb [configuration directory]")
        sys.exit(1)

    configs = load_configs(configdir)
    template = _TEMPLATE

    text = ''
    for menu in MENUS.keys():
        text += '<tr><th colspan="5"><a href="#%s">%s</a></th></tr>\n' % \
            (menu, MENUS[menu])
    text += '<tr><th colspan="5"><hr></th></tr>\n'
    for menu in MENUS.keys():
        menuconfigs = [cf for cf in configs.values() if cf['menu'] == menu]
        text += _add_submenu(menu, menuconfigs)

    template = template.replace('@TABLE_ROWS@', text)
    print(template)

main()
