import struct
from copy import copy, deepcopy

from secml.array import CArray
from secml_malware.attack.blackbox.c_blackbox_problem import CBlackBoxProblem
from secml_malware.attack.blackbox.c_wrapper_phi import CWrapperPhi
import numpy as np

class CBlackBoxHeaderEvasionProblem(CBlackBoxProblem):
	def __init__(
			self,
			model_wrapper: CWrapperPhi,
			population_size: int,
			optimize_all_dos: bool = False,
			iterations: int = 100,
			is_debug: bool = False,
			penalty_regularizer: float = 0,
			invalid_value: int = 256
	):
		super(CBlackBoxHeaderEvasionProblem, self).__init__(model_wrapper,
															latent_space_size=58,
															iterations=iterations,
															population_size=population_size,
															is_debug=is_debug,
															penalty_regularizer=penalty_regularizer)
		self.optimize_all_dos = optimize_all_dos
		self.invalid_value = invalid_value
		self.indexes_to_perturb = list(range(2, 60))

	def init_starting_point(self, x : CArray):
		self.indexes_to_perturb = list(range(2, 60))
		if self.optimize_all_dos:
			pe_index = struct.unpack('<I', bytes(x[0,60:64].tolist()[0]))[0]
			self.indexes_to_perturb += list(range(64, pe_index))
		self.latent_space_size = len(self.indexes_to_perturb)
		super(CBlackBoxHeaderEvasionProblem, self).init_starting_point(x)

	def apply_feasible_manipulations(self, t, x : CArray):
		byte_values = (t * 255).astype(np.int)
		x_adv = deepcopy(x)
		for i, index in enumerate(self.indexes_to_perturb):
			x_adv[0, index] = byte_values[i]
		return CArray(x_adv)