import os
import sys

import waflib.Logs

from waflib.Configure import conf

@conf
def get_bluetooth_fw_node(ctx, variant='main', subdir=None):
    subpath = ('src/bluetooth-fw/da1468x/controller/{variant}/bt_da14681_{variant}.bin'
               .format(variant=variant))
    if subdir:
        subpath = os.path.join(subdir, subpath)
    return ctx.path.get_bld().make_node(subpath)


@conf
def get_bluetooth_fw_node_prf(ctx):
    return ctx.get_bluetooth_fw_node(subdir='prf')


@conf
def get_bluetooth_fw_node_boot(ctx):
    return ctx.get_bluetooth_fw_node('boot')


@conf
def uses_dialog_bluetooth(ctx):
    return 'da14681' in ctx.env.bt_controller


def _recurse(ctx):
    if ctx.env.bt_controller == 'cc2564x':
        # TODO: replace with real FW
        ctx.recurse('stub')
    elif ctx.uses_dialog_bluetooth():
        ctx.recurse('da1468x')
    elif ctx.env.bt_controller == 'qemu':
        ctx.recurse('qemu')
    else:
        ctx.fatal('Invalid bt controller {}'.format(ctx.env.bt_controller))


def options(opt):
    opt.add_option('--bt_controller', action='store', default=None,
                   help='Override Bluetooth controller to build for',
                   choices=['da14681-01', 'da14681-00', 'cc2564x', 'qemu'])
    opt.recurse('da1468x')


def configure(conf):
    prev_variant = conf.variant
    prev_env = conf.env

    if conf.options.bt_controller:
        bt = conf.options.bt_controller
        conf.env.bt_controller = bt
    else:
        # If option wasn't specified, assume main wscript has set env.bt_controller.
        # Act as if the option was set, so recurse'd wscripts can use the option.
        conf.options.bt_controller = conf.env.bt_controller

    waflib.Logs.pprint('CYAN', 'Using Bluetooth controller: {}'
                       .format(conf.env.bt_controller))
    _recurse(conf)

    conf.variant = prev_variant
    conf.env = prev_env


def build(bld):
    prev_env = bld.env
    _recurse(bld)
    bld.env = prev_env

# vim:filetype=python
