''' Create the legacy hwdb table using data in config files '''

import glob
import os
import sys
import yaml

import database

HEADER = '''
# LIRC - Hardware DataBase
#
# THIS FILE IS DEPRECATED AND WILL BE REMOVED IN NEXT RELEASE.
#
# This is a generated file. Do not edit.
#
# The file lists all the remote controls supported by LIRC
# in a parseable form. It's legacy file kept for compatiblity.
# The current yaml files configs/*.conf should be a better
# source in most cases.
#
# The format is:
#
# [remote controls type]
# description;driver;lirc driver;HW_DEFAULT;lircd_conf;
#
# The HW_DEFAULT field is always empty.
#
#

'''

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'
}


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 table rows. '''

    def getit(remote,  what, driver,  _default=''):
        ''' Get a value from a remote, use default if not existing. '''
        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 = '[' + MENUS[menu] + ']\n'
    for remote in configs:
        try:
            driver = db.drivers[remote['driver']]
        except KeyError:
            driver = None
        if getit(remote, 'driver', driver)  == "none":
            continue
        s += getit(remote, 'label', driver) + ';'
        s += getit(remote, 'modinit', driver).replace(';', ',') + ';'
        s += getit(remote, 'driver', driver) + ';;'
        files = [getit(remote, 'lircd_conf', driver),
                 getit(remote, 'lircmd.conf', driver)]
        remotes = db.remotes_by_driver(driver)
        if remotes:
            files.extend(remotes)
        files = [f for f in files if f]
        s += ' '.join(files).replace('run_select_any_config', '') + ';\n'
    return s

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: data2hwd [configuration directory]")
        sys.exit(1)

    db = database.Database(configdir, yamldir)
    print(HEADER)
    for menu in MENUS.keys():
        try:
            menuconfigs = [cf for cf in db.configs.values()
                           if cf['menu'] == menu]
            print(_add_submenu(menu, menuconfigs, db))
        except KeyError:
            print("No menu in " + db.configs['id'])


if __name__ == '__main__':
    main()


# vim: set expandtab ts=4 sw=4:
