#!/usr/bin/env python3
import __py_include
import logging
import time

from homekit.api import WebApiClient, RequestParams
from homekit.config import config
from homekit.media import SoundRecordClient
from homekit.util import Addr

logger = logging.getLogger(__name__)


# record callbacks
# ----------------

def record_error(info: dict, userdata: dict):
    node = userdata['node']
    # TODO


def record_finished(info: dict, fn: str, userdata: dict):
    logger.info('record finished: ' + str(info))

    node = userdata['node']
    api.upload_recording(fn, node, info['id'], int(info['start_time']), int(info['stop_time']))


# api client callbacks
# --------------------

def api_error_handler(exc, name, req: RequestParams):
    if name == 'upload_recording':
        logger.error('failed to upload recording, exception below')
        logger.exception(exc)

    else:
        logger.error(f'api call ({name}, params={req.params}) failed, exception below')
        logger.exception(exc)


def api_success_handler(response, name, req: RequestParams):
    if name == 'upload_recording':
        node = req.params['node']
        rid = req.params['record_id']

        logger.debug(f'successfully uploaded recording (node={node}, record_id={rid}), api response:' + str(response))

        # deleting temp file
        try:
            os.unlink(req.files['file'])
        except OSError as exc:
            logger.error(f'error while deleting temp file:')
            logger.exception(exc)

        record.forget(node, rid)


if __name__ == '__main__':
    config.load_app('test_record_upload')

    nodes = {}
    for name, addr in config['nodes'].items():
        nodes[name] = Addr(addr)
    record = SoundRecordClient(nodes,
                               error_handler=record_error,
                               finished_handler=record_finished,
                               download_on_finish=True)

    api = WebApiClient()
    api.enable_async(error_handler=api_error_handler,
                     success_handler=api_success_handler)

    record_id = record.record('localhost', 3, {'node': 'localhost'})
    print(f'record_id: {record_id}')

    while True:
        try:
            time.sleep(0.1)
        except (KeyboardInterrupt, SystemExit):
            break