# -*- coding: utf-8 -*-
"""
    Implementation of RCON service
    
Copyright 2024-2025 NXP
SPDX-License-Identifier: BSD-3-Clause

"""

import gdb  # @UnresolvedImport  # pylint: disable=F0401
import argparse
import shlex

from rcon.gdbcommands import cmd_name
from errors import Ok, Result, Error, ErrorCode

###################################################################
######### Start RCON services command
###################################################################
class RconServices(gdb.Command):
    """
        Start RCON services.
    """

    #make sure that invoke gets called only once
    instance = None

    def __init__(self):
        super(RconServices, self).__init__(cmd_name.CMD_RCON_SERVICES,
        gdb.COMMAND_SUPPORT)
        parser = argparse.ArgumentParser(description='DS for Vision \
            RCON Programming services.', fromfile_prefix_chars='|>@')
        group = parser.add_argument_group('Target Configuration')
        group.add_argument('-r', '--reset_timeout',
                            metavar = '',
                            type = int,
                            default = 1,
                            help = 'reset timeout')
        parser.add_argument('--probe',
                            metavar = '',
                            help = 'specify connection probe used to connect to \
                            target or implicitly use usb if no option is provided')
        parser.add_argument('--ccsip',
                            metavar = '',
                            default = '',
                            help = 'specify ccs connection address and \
                            port like 127.0.0.1:41475')
        parser.add_argument('--gtaip',
                            metavar = '',
                            default = '',
                            help = 'specify debugger port')
        parser.add_argument('-t', '--timeout', 
                            metavar = '',
                            type = int,
                            default = 100,
                            help = 'specify operations timeout - useful in case \
                            of writing a big kernel image')
        parser.add_argument('--jtag_speed',
                            metavar = '',
                            type = int,
                            default = 16000,
                            help = 'specify jtag speed')
        parser.add_argument('-i', '--interactive',
                            action="store_true",
                            help = 'enter interactive mode where user can \
                            configure target connection')
        parser.add_argument('--reset_delay', 
                            metavar = '',
                            type = int,
                            default = 1,
                            help = 'specify reset delay')
        parser.add_argument('--reset_type', 
                            metavar = '',
                            default = 'default',
                            help = 'specify reset type')
        parser.add_argument('--rconscript', 
                            metavar = '',
                            default = '',
                            help = 'specify device RCON script')
        parser.add_argument('--log', 
                            metavar = '',
                            type = self.str2bool,
                            default = False,
                            help = 'enable log')
        parser.add_argument('--secure_type', 
                            metavar = '',
                            default = '',
                            help = 'secure_type')
        parser.add_argument('--secure_key', 
                            metavar = '',
                            default = '',
                            help = 'secure_key')
        parser.add_argument('--target_lifecycle',
                            metavar = '',
                            default = '',
                            help = 'specify target lifecycle')
        self._parser = parser

    def invoke(self, argument):
        self.dont_repeat()
        ret = False
        try:
            ret = self.start_service(argument)
        except SystemExit:
            pass
        return ret

    def dont_repeat(self):
        gdb.Command.dont_repeat(self)
        
    def str2bool(self, v):
        if v.lower() in ('yes', 'true', 't', 'y', '1'):
            return True
        elif v.lower() in ('no', 'false', 'f', 'n', '0'):
            return False
        else:
            Result(Error(ErrorCode.ValueError, 'F-ERROR: Boolean value expected.')).unwrap()

    def start_service(self, argument):
        args = self._parser.parse_args(shlex.split(argument))
        ret = False
        if RconServices.instance is None:
            from rcon.scripts.rcon_init import start
            ret = start(args)
            if ret is True:
                RconServices.instance = self
            else:
                Result(Error(ErrorCode.RCONInitError, 'Could not initialize RCON service')).unwrap()
        else:
            gdb.write('Service already started\n')
        return ret


###################################################################
######### Register RCON services ##########
###################################################################
def load_rcon_services():
    """
        Add RCON programmer services
    """
    RconServices()

def start_rcon_services(argument):
    """
        Add RCON programmer services
    """
    instance = RconServices()
    return instance.invoke(argument)

