#!/usr/bin/env python3
# SPDX-License-Identifier: GPL-3.0-or-later
# Copyright (C) 2018 Takashi Sakamoto

from hinawa_utils.misc.cui_kit import CuiKit
from hinawa_utils.oxfw.oxfw_unit import OxfwUnit
from hinawa_utils.ta1394.audio import AvcAudio

def handle_current_status(unit, args):
    print('Current status:')
    print('  Packet Streaming:')
    print('    running:          {0}'.format(unit.get_property('streaming')))
    fmts = unit.get_current_stream_formats()
    print('    sampling-rate:    {0}'.format(fmts['playback']['sampling-rate']))
    print('Channel:')
    data = AvcAudio.get_feature_volume_state(unit.fcp, 0, 'current', 1, 0)
    db = AvcAudio.parse_data_to_db(data)
    print('  volume: {0}'.format(db))
    if AvcAudio.get_feature_mute_state(unit.fcp, 0, 'current', 1, 0):
        mute = 'on'
    else:
        mute = 'off'
    print('  mute: {0}'.format(mute))
    print('ASIC information:')
    print('  type:             {0}'.format(unit.hw_info['asic-type']))
    print('  ID:               {0}'.format(unit.hw_info['asic-id']))
    print('  firmware version: {0}'.format(unit.hw_info['firmware-version']))
    return True

def handle_output_volume(unit, args):
    ops = ('set', 'get')
    if len(args) > 0 and args[0] in ops:
        op = args[0]
        if op == ops[0] and len(args) == 2:
            db = float(args[1])
            data = AvcAudio.build_data_from_db(db)
            AvcAudio.set_feature_volume_state(unit.fcp, 0, 'current', 1, 0,
                                              data)
        else:
            data = AvcAudio.get_feature_volume_state(unit.fcp, 0, 'current', 1,
                                                     0)
            print(AvcAudio.parse_data_to_db(data))
        return True
    print('Arguments for output-volume command:')
    print('  output-volume OP CH [dB]')
    print('    OP: [{0}]'.format('|'.join(ops)))
    print('    dB: [-128.0..128.0] if OP=set')
    return False

def handle_output_mute(unit, args):
    ops = ('set', 'get')
    if len(args) > 0 and args[0] in ops:
        op = args[0]
        if op == ops[0] and len(args) == 2:
            value = int(args[1])
            AvcAudio.set_feature_mute_state(unit.fcp, 0, 'current', 1, 0, value)
        else:
            print(AvcAudio.get_feature_mute_state(unit.fcp, 0, 'current', 1, 0))
        return True
    print('Arguments for output-mute command:')
    print('  output-mute OPERATION CH [VALUE]')
    print('    OPERATION: {0}'.format(', '.join(ops)))
    print('    VALUE:     0, 1')
    return False

cmds = {
    'current-status':   handle_current_status,
    'output-volume':    handle_output_volume,
    'output-mute':      handle_output_mute,
}

fullpath = CuiKit.seek_snd_unit_path()
if fullpath:
    unit = OxfwUnit(fullpath)
    CuiKit.dispatch_command(unit, cmds)
