# -*- coding: utf-8 -*-
"""
    Custom GDB commands for thread awareness.


 Copyright 2023 NXP

 NXP Confidential. This software is owned or controlled by NXP and may only be
 used strictly in accordance with the applicable license terms. By expressly
 accepting such terms or by downloading, installing, activating and/or otherwise
 using the software, you are agreeing that you have read, and that you agree to
 comply with and are bound by, such license terms. If you do not agree to be
 bound by the applicable license terms, then you may not retain, install,
 activate or otherwise use the software.


"""

import gdb
import os
import sys
import time

CURRENT_DIR = ''.join([os.path.dirname(os.path.realpath(__file__)), '/'])
sys.path.insert(0, CURRENT_DIR)
sys.path.insert(0, CURRENT_DIR + "/../../utils")

class TimeCommand(gdb.Command):
    """Show GDB execution time for specified command.
When iterations is higer than 1, it reports the max, min and average execution time.

usage: time [times] [command]

optional arguments:
    times       - iterations number (default 1)
    command     - GDB command to execute
    """

    def __init__(self):
        """
        Constructor
        """
        super(TimeCommand, self).__init__("time", gdb.COMMAND_USER)

    def get_iterations(self, args):
        iters = 1
        argv = gdb.string_to_argv(args)

        if not len(argv):
            return (0, None)

        try:
            iters = int(argv[0])
            args = args.replace(argv[0] + ' ', '')
        except:
            pass

        return (iters, args)

    def invoke(self, args, from_tty):
        """ Called when the command is invoked """
        iters, args = self.get_iterations(args)

        if iters:
            min = sys.maxint
            max = 0
            total = 0

            for i in range(0, iters):
                start=time.time()
                gdb.execute(args)
                diff = time.time() - start

                if min > diff:
                    min = diff

                if max < diff:
                    max = diff

                total += diff

            avg = total / iters

            if iters > 1:
                gdb.write("{0}x'{1}' took: min {2:.2f} s, avg: {3:.2f} s, max: {4:.2f} s\n".format(iters, args, min, avg, max))
            else:
                gdb.write("'{0}' tooks: {1:.2f} s\n".format(args, total))

def create_commands():
    """Create GDB commands."""
    TimeCommand()