# -*- coding: utf-8 -*-
# Copyright 2018-2020, 2022, 2025 NXP
# SPDX-License-Identifier: BSD-3-Clause

import  os
import gdb
from flash.scripts.remote import execute_remote

"""Flash Commands interface implementation"""
class FlashCommandsImplBinary(object):
    def __init__(self, from_tty, debug=False):
        W_DIR = os.path.dirname(os.path.realpath(__file__))
        self.from_tty = from_tty
        self.r_file = W_DIR + "/read.dat"
        self.w_file = W_DIR + "/write.dat"
        self.v_file = W_DIR + "/verifyCRC.dat"
        self.debug = debug

    def __del__(self):
        try:
            os.remove(self.r_file)
        except:
            pass
        try:
            os.remove(self.w_file)
        except:
            pass

    def verify(self, offset, size, crc):
        cmd_string = "mon flash verifyCRC32 binary %s offset 0x%x size 0x%x crc 0x%x" % (self.v_file, offset, size, crc)
        self._log(cmd_string)
        execute_remote(cmd_string, self.from_tty, no_wait=False)
        return self._readCRC32()

    def erase(self, offset, size):
        cmd_string = "mon flash erase offset 0x%x size 0x%x" % (offset, size)
        self._log(cmd_string)
        execute_remote(cmd_string, self.from_tty, no_wait=False)

    def read(self, offset, size):
        cmd_string = "mon flash dump binary %s offset 0x%X size 0x%X" % (self.r_file, offset, size)
        self._log(cmd_string)
        execute_remote(cmd_string, self.from_tty, no_wait=False)
        return self._read()

    def write(self, offset, data):
        self._write(data)
        cmd_string = "mon flash write binary %s offset 0x%X" % (self.w_file, offset)
        self._log(cmd_string)
        execute_remote(cmd_string, self.from_tty, no_wait=False)

    def _read(self):
        f = open(self.r_file, 'rb')
        data = f.read()
        f.close()
        return data

    def _write(self, data):
        f = open(self.w_file, 'wb')
        f.write(bytearray(data))
        f.close()

    def _readCRC32(self):
        f = open(self.v_file, 'rb')
        data = f.read()
        f.close()
        return data
        
    def _log(self, str):
        if self.debug:
            gdb.write('%s\n' % str)
