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

import glob
import os
import sys
import yaml

import database


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 setup</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 _add_submenu(menu, configs, db):
    ''' 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:
            driver = db.drivers[remote['driver']]
        except KeyError:
            driver = None
        try:
            value = remote[what]
        except KeyError:
            if not driver:
                return _default
            try:
                value = driver[what]
            except KeyError:
                return _default
        if isinstance(value, list):
            return ' '.join(value)
        return value

    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', '')):
        if remote['id'] == 'irlink':
            pass
        if remote['id'] == 'none':
            continue
        s += '<tr>'
        s += '<td>' + getit(remote, 'label') + '</td>'
        s += '<td>' + getit(remote, 'modinit') + '</td>'
        s += '<td>' + getit(remote, 'driver') + '</td>'
        s += '<td>'
        files = getit(remote, 'lircd_conf') + ' ' + getit(remote, 'lircmd_conf')
        driver = remote['driver']
        files += ' '.join(db.remotes_by_driver(driver))
        files += ' '.join(db.lircmd_by_driver(driver))
        s += files
        s += '</td>'
        s += '<td>' + getit(remote, 'type') + '</td>'
        s += '</tr>'
    return s.replace('& ', '&amp; ')


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

    db = database.Database(configdir, yamldir)
    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 db.configs.values()
                       if cf['menu'] == menu]
        text += _add_submenu(menu, menuconfigs, db)

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


main()
