# -*- coding: utf-8 -*-
"""
    Implementation of RCON Programmer utility methods

Copyright 2024 NXP
SPDX-License-Identifier: BSD-3-Clause

"""
import gdb
import string
import os
import os.path
from errors import Result, Error, ErrorCode, Ok, safecall

# Enable or disable warning messages
__show_warning = False

def string_to_value(str):
    try:
        if str.startswith('0x'):
            return int(str, 16)
        return int(str)
    except BaseException as e:
        Result(Error(ErrorCode.ValueError, str(e))).unwrap()

def is_hex_sequence(seq):
    if seq.startswith('0x'):
        hex_digits = set(string.hexdigits)
        return all(c in hex_digits for c in seq[2:])
    return False

@safecall
def gdb_execute(command, from_tty = False, to_string = False, check_warning = True):
    """
        Execute a GDB command, remove the echo if it appears,
        handle the exception
    """

    #if it is a monitor command issue warning
    if check_warning is True and command and command.startswith('mon'):
        gdb_warning("Warning: monitor command called through gdb.execute. \n")

    try:
        result = gdb.execute(command, from_tty, to_string)
        if result:
            result = result.rstrip("\n")
        echo_command = "+" + command + "\n"
        if result is not None and result.startswith(echo_command):
            return Result(Ok(result[len(echo_command):]))
        else:
            return Result(Ok(result))
    except gdb.error as exc:
        cmd = 'mon errorinfo'
        error_msg = gdb_execute(cmd, from_tty, True)
        error_msg += "on command:%s" % command
        return Result(Error(ErrorCode.UndefinedError, error_msg))

def gdb_warning(warning_msg):
    global __show_warning

    if __show_warning is True:
        gdb.write(warning_msg)

