#!/usr/bin/env python

# ------------------------------------------------------------------------
#
#  chirp-audio-read: Read a chirp payload from an audio file.
#
#  This file is part of the Chirp Connect Python SDK.
#  For full information on usage and licensing, see https://chirp.io/
#
#  Copyright (c) 2011-2018, Asio Ltd.
#  All rights reserved.
#
# ------------------------------------------------------------------------

import argparse
import configparser
import os
import sys
import wave

from chirpsdk import ChirpConnect, CallbackSet, CHIRP_SDK_BUFFER_SIZE


class Callbacks(CallbackSet):

    def __init__(self, args):
        self.args = args

    def on_receiving(self, channel):
        """ Called when a chirp frontdoor is detected """
        print('Receiving data')

    def on_received(self, payload, channel):
        """
        Called when an entire chirp has been received.
        Note: A length of 0 indicates a failed decode.
        """
        if payload is None:
            print('Decode failed!')
        else:
            if self.args.unicode:
                print('Received ' + payload.decode('utf-8'))
            elif self.args.hex:
                print('Received ' + str(payload))
            else:
                print('Received: ' + str(list(payload)))


def main(args):
    # ------------------------------------------------------------------------
    # Read ~/.chirprc
    # ------------------------------------------------------------------------
    config = configparser.ConfigParser()
    config.read(os.path.expanduser('~/.chirprc'))

    app_key = config.get('default', 'app_key')
    app_secret = config.get('default', 'app_secret')
    app_config = config.get('default', 'app_config')

    # ------------------------------------------------------------------------
    # Initialise the Connect SDK.
    # ------------------------------------------------------------------------
    sdk = ChirpConnect(app_key, app_secret, app_config)
    print(str(sdk))
    if args.network_config:
        sdk.set_config_from_network()

    # ------------------------------------------------------------------------
    # Disable audio playback.
    # ------------------------------------------------------------------------
    sdk.audio = None
    sdk.set_callbacks(Callbacks(args))
    sdk.start(send=False, receive=True)

    w = wave.open(args.input_file, 'r')
    data = w.readframes(w.getnframes())
    sdk.sample_rate = w.getframerate()

    for f in range(0, len(data), CHIRP_SDK_BUFFER_SIZE):
        if w.getsampwidth() == 2:
            sdk.process_shorts_input(data[f: f + CHIRP_SDK_BUFFER_SIZE])
        elif w.getsampwidth() == 4:
            sdk.process_input(data[f: f + CHIRP_SDK_BUFFER_SIZE])

    sdk.stop()
    sdk.close()


if __name__ == '__main__':
    # ------------------------------------------------------------------------
    # Parse command-line arguments.
    # ------------------------------------------------------------------------
    parser = argparse.ArgumentParser(
        description='Chirp Connect Audio Reader',
        epilog='Reads a .wav file containing Chirp Connect audio payloads, and outputs any payloads found'
    )
    parser.add_argument('input_file', help='Input file')
    parser.add_argument('-u', '--unicode', action='store_true', help='Parse payloads as unicode')
    parser.add_argument('-x', '--hex', action='store_true', help='Parse payloads as hexstrings')
    parser.add_argument('--network-config', action='store_true', help='Optionally download a config from the network')
    args = parser.parse_args()

    main(args)
