# -*- coding: utf-8 -*-
"""
    Implementation of Flash Programmer protect command

Copyright 2015 Freescale Semiconductor, Inc.
Copyright 2017-2018, 2024 NXP.

SPDX-License-Identifier: BSD-3-Clause

"""

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

from flash.gdbcommands.base_command import CwFlashBase
from flash.gdbcommands.cmd_name import CMD_CW_FLASH_PROTECT

from flash.scripts.utils import string_to_offset
from flash.scripts.utils import string_to_size
from flash.scripts.utils import size_to_human_readable
from flash.scripts.remote import execute_remote

###################################################################
######### flash programmer protect command
###################################################################
class CwFlashProtect(CwFlashBase):
    """
usage: [-h] offset size

S32DS Flash Programming protect command.

positional arguments:
  offset      offset in device address range
  size        size of memory section to be protected

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

    def __init__(self):
        """
            Register new command with GDB
            Add a parameter parser to easily specify positional offset and size
            parameters
        """
        super(CwFlashProtect, self).__init__(CMD_CW_FLASH_PROTECT,
        gdb.COMMAND_USER, gdb.COMPLETE_COMMAND)
        parser = argparse.ArgumentParser(description='S32DS \
                                         Flash Programming protect command.')
        parser.add_argument('offset',
                            type = string_to_offset,
                            help = 'offset in device address range')
        parser.add_argument('size',
                            type = string_to_size,
                            help = 'size of memory section to be protected')
        self._parser = parser
        CwFlashProtect.print_result = None

        # Don't print on the screen while progress bar is in place. Save the output and
        # print after closing the progress bar.
        self.output = ""

    def execute(self, args, from_tty):
        """
            Execute command called with args parameters
            Build command string in the form of a monitor command
            and call internal gdb execution.
        """

        cmd_string = 'mon flash protect offset %d size %d' % (args.offset, args.size)

        #execute command
        execute_remote(cmd_string, from_tty, no_wait = True)

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

    def show_result(self):
        summary = 'Protect %s in %.2fs\n' % \
            (size_to_human_readable(self._args.size), self._time)
        gdb.write(summary)

def create_command():
    """
        Instantiate flash programmer protect command
    """
    CwFlashProtect()
