#!/usr/bin/env python3

import argparse
import asyncio
import qmsk.cli
import qmsk.e2.client
import qmsk.e2.presets
import qmsk.net.tcp

import logging; log = logging.getLogger('qmsk-e2-client')

class Client:
    def __init__(self, loop):
        self.loop = loop

    @asyncio.coroutine
    def start (self, args):
        try:
            self.client = yield from qmsk.e2.client.apply(args)
        except qmsk.net.tcp.Error as error:
            log.error("%s: failed to connect: %s", args.e2_host, error)
            return 1
        
        self.presets = qmsk.e2.presets.apply(args)

        if not self.presets.presets:
            log.error("no presets given")
            return 1

        return 0

    @asyncio.coroutine
    def run (self, args):
        if args.preset is not None:
            try:
                yield from self.client.PRESET_recall(args.preset)
            except qmsk.e2.client.CommandError as error:
                log.error("%s: PRESET_recall(%s): %s", self.client, args.preset, error)
                return 1

        if args.transition is not None:
            try:
                yield from self.client.ATRN(args.transition)
            except qmsk.e2.client.CommandError as error:
                log.error("%s: ATRN(%s): %s", self.client, args.transition, error)
                return 1
        
        return 0
   
def main (argv):
    parser = qmsk.cli.parser()
    qmsk.e2.client.parser(parser)
    qmsk.e2.presets.parser(parser)

    parser.add_argument('--preset',         metavar='PRESET', type=int,
            help="Recall preset")
    parser.add_argument('--cut',            dest='transition', action='store_const', const=0,
            help="Cut transition")
    parser.add_argument('--autotrans',      dest='transition', action='store_true',
            help="Auto transition")
    parser.add_argument('--transition',     dest='transition', metavar='FRAMES', type=int,
            help="Timed transition")
    
    # start
    args = qmsk.cli.parse(parser, argv)
    loop = asyncio.get_event_loop()

    # start
    client = Client(loop)
    do_start = asyncio.async(client.start(args))

    try:
        log.info("start event loop")
        out = loop.run_until_complete(do_start)

    except Exception as error:
        log.exception("Failed to start")
        return 1

    else:
        if out:
            return out
    
    # run
    do_start = asyncio.async(client.run(args))

    try:
        log.info("run event loop")
        out = loop.run_until_complete(do_run)

    except Exception as error:
        log.exception("Failed to run")
        return 1

    else:
        if out:
            return out

    log.info("exit")
    return 0

if __name__ == '__main__':
    qmsk.cli.main(main)
