#!/usr/bin/env python
"""
Output X-Plane performance via UDP. Based partially on amerigo. Check
out github/kiike/amerigo for more info.

Copyright (c) 2016 Enric Morales <me@enric.me>

Permission to use, copy, modify, and distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.

THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
"""

import argparse
import logging as log
import socket
import struct
import sys

UDP_ADDR = "0.0.0.0"
UDP_PORT = 49000


def split_payload(payload, size=36):
    """
    Yield every 36-piece chunk of `payload`
    """

    for i in range(0, len(payload) // size):
        yield payload[size * i:size * (i + 1)]


def parse_stream(input_bytes):
    """
    Return a dictionary composed of the parsed binary 'data'.

    input_bytes -> {key1: value1, .., keyN: valueN}
    input_bytes ::= binary literal
    """

    # Relate the dataset (integer key) to the data (list of values)
    rosetta = {0:  ["fact_sec", "fsim_sec", "frame_time", "cpu_time",
                    "gpu_time", "grnd_ratio", "flit_ratio", ""]
              }

    header = input_bytes[0:5]
    payload = input_bytes[5:]

    if header == b"DATA@":
        output = {}
        for piece in split_payload(payload):
            msg = struct.unpack_from("iffffffff", piece)
            data_set = msg[0]
            data = msg[1:]
            log.debug("<<< idx:{} idx:{}".format(data_set, data))

            if data_set in rosetta:
                # Append the translated 'data_set' to the output dict
                translated = dict(zip(rosetta[data_set], data))
                output.update(translated)
            else:
                msg = "Unimplemented data set idx:{} data:{}"
                log.warning(msg.format(data_set, data))

        log.debug(">>> {}".format(output))
        return output


def interpret(address, port):
    """
    Bind to a socket, parse the input and write to file.
    """

    # Bind to an internet-facing UDP socket
    udp_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    log.info("Binding to {}:{}".format(address, port))
    udp_socket.bind((address, port))

    while True:
        # Receive with a buffer of 1024 bytes
        data, _ = udp_socket.recvfrom(1024)
        parsed = parse_stream(data)

        act_fps = parsed['fact_sec']
        gpu_fps = 1 / parsed['gpu_time']
        cpu_fps = 1 / parsed['cpu_time']
        out_format = "\rACTIVE: {:.4}, GPU: {:.4}, CPU: {:.4}\t\t\t"
        sys.stdout.write(out_format.format(act_fps, gpu_fps, cpu_fps))
        sys.stdout.flush()


def main():
    """
    Parse arguments, create interpreter and web server threads.
    """

    args = argparse.ArgumentParser()
    args.add_argument("-p", "--port", type=int, default=UDP_PORT,
                      help="port to bind to (default: %(default)s)")
    args.add_argument("-a", "--address", default=UDP_ADDR,
                      help="address to bind to (default: %(default)s)")
    args.add_argument("-d", "--debug", const=log.DEBUG, nargs="?",
                      dest="loglevel", default=log.WARNING,
                      help="turn on debugging")
    args.add_argument("-v", "--verbose", const=log.INFO, nargs="?",
                      dest="loglevel",
                      help="turn on verbose output")
    args = args.parse_args()

    log.basicConfig(level=args.loglevel)

    interpret(args.address, args.port)

if __name__ == "__main__":
    main()
