# Path: btchip/btchipException.py
# class BTChipException(Exception):
# 
# 	def __init__(self, message, sw=0x6f00):
# 		self.message = message
# 		self.sw = sw
# 
# 	def __str__(self):
# 		buf = "Exception : " + self.message
# 		return buf


import struct
from .btchipException import BTChipException
		blockSize = packetSize - 7
	else:
		blockSize = len(command)
	result += command[offset : offset + blockSize]
	offset = offset + blockSize
	while offset != len(command):
		result += struct.pack(">HBH", channel, 0x05, sequenceIdx)
		sequenceIdx = sequenceIdx + 1
		if (len(command) - offset) > packetSize - 5:
			blockSize = packetSize - 5
		else:
			blockSize = len(command) - offset
		result += command[offset : offset + blockSize]
		offset = offset + blockSize
	while (len(result) % packetSize) != 0:
		result += b"\x00"
	return bytearray(result)

def unwrapResponseAPDU(channel, data, packetSize):
	sequenceIdx = 0		
	offset = 0
	if ((data is None) or (len(data) < 7 + 5)):
		return None
	if struct.unpack(">H", data[offset : offset + 2])[0] != channel:
		raise BTChipException("Invalid channel")
	offset += 2
	if data[offset] != 0x05:
		raise BTChipException("Invalid tag")
	offset += 1
	if struct.unpack(">H", data[offset : offset + 2])[0] != sequenceIdx:

# Path: btchip/btchipException.py
# class BTChipException(Exception):
# 
# 	def __init__(self, message, sw=0x6f00):
# 		self.message = message
# 		self.sw = sw
# 
# 	def __str__(self):
# 		buf = "Exception : " + self.message
# 		return buf


# Path: btchip/ledgerWrapper.py
import struct
from .btchipException import BTChipException

		blockSize = packetSize - 7
	else:
		blockSize = len(command)
	result += command[offset : offset + blockSize]
	offset = offset + blockSize
	while offset != len(command):
		result += struct.pack(">HBH", channel, 0x05, sequenceIdx)
		sequenceIdx = sequenceIdx + 1
		if (len(command) - offset) > packetSize - 5:
			blockSize = packetSize - 5
		else:
			blockSize = len(command) - offset
		result += command[offset : offset + blockSize]
		offset = offset + blockSize
	while (len(result) % packetSize) != 0:
		result += b"\x00"
	return bytearray(result)

def unwrapResponseAPDU(channel, data, packetSize):
	sequenceIdx = 0		
	offset = 0
	if ((data is None) or (len(data) < 7 + 5)):
		return None
	if struct.unpack(">H", data[offset : offset + 2])[0] != channel:
		raise BTChipException("Invalid channel")
	offset += 2
	if data[offset] != 0x05:
		raise BTChipException("Invalid tag")
	offset += 1
	if struct.unpack(">H", data[offset : offset + 2])[0] != sequenceIdx:

		raise BTChipException("Invalid sequence")