# -*- coding: utf-8 -*-
"""
    Implementation of RCON write command

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

"""

import gdb   # @UnresolvedImport  # pylint: disable=F0401
import argparse
import importlib
from math import ceil

from rcon.gdbcommands.base_command import RconBase
from rcon.gdbcommands.cmd_name import CMD_RCON_WRITE

from rcon.scripts.utils import string_to_value, is_hex_sequence
from errors import Result, Error, ErrorCode

global RCON
###################################################################
#########  RCON write command
###################################################################
class RconWrite(RconBase):
    """
usage: Write RCON value. Parameters: [-h] value

S32DS  RCON write command.

positional arguments:
    
  address              Start address for the writting. Maximum of 8 consecutive bytes supported.

  value                32b RCON value. Use rcon_help for complete expected RCON values and additional help.
  

optional arguments:
  -h, --help            show this help message and exit
    """

    def __init__(self):
        """
            Register new command with GDB
        """
        super(RconWrite, self).__init__(CMD_RCON_WRITE,
        gdb.COMMAND_USER, gdb.COMPLETE_FILENAME)
        parser = argparse.ArgumentParser(usage='[-h] value',
                                         description='S32DS \
                                         RCON write command.')
        parser.add_argument('address',
                            type = string_to_value,
                            help = 'Start address for the write operation. Must be hexadecimal format.')
        parser.add_argument('data',
                            #type = string_to_value,
                            help = 'RCON value to write')
        self._parser = parser


    def execute(self, args):
        """
            Execute command called with params parameters
            Build command string in the form of a monitor command
            and call internal gdb execution.
        """
        if args.data is not None or args.address is not None:
            if is_hex_sequence(args.data):
                no_of_chars = len(args.data) - 2
                if no_of_chars % 2 != 0:
                    no_of_chars += 1
                no_of_bytes = no_of_chars // 2
                RCON.RCON_WRITE(args.address, string_to_value(args.data), no_of_bytes)
            else:
                Result(Error(ErrorCode.RCONParameterError,'F-ERROR: data must be hex sequence.')).unwrap()
        else:
            Result(Error(ErrorCode.RCONParameterError,'F-ERROR: command parameter missing')).unwrap()


    def begin_command(self):
        gdb.write('Writing....\n')

    def end_command(self):
        gdb.write('Write complete....\n')

def create_command(RCONfilePath):
    """
        Instantiate RCON write command
    """
    global RCON 
    RCON = importlib.import_module(RCONfilePath[:-3])
    RconWrite()
