import os
import subprocess
import sys
from . import tools

try :
	testpath = os.path.dirname(os.path.abspath(os.path.join(os.getcwd(), sys.argv[0])))
	sys.path.append(testpath)
	import config

	SRCDIR = os.path.abspath(config.SRCDIR)
	BUILDDIR = os.path.abspath(config.BUILDDIR)
	os.chdir(testpath)

except:
	print('ERROR: missing config.py, re-run configure script.', file=sys.stderr)
	sys.exit(1)

class Architecture:
	KnownArchitectures = {
		'x64'			: 'x64',
		'x86-64'		: 'x64',
		'x86_64'		: 'x64',
		'x86'			: 'x86',
		'i386'		: 'x86',
		'i486'		: 'x86',
		'i686'		: 'x86',
		'Intel 80386'	: 'x86',
		'arm'			: 'arm',
		'ARM'			: 'arm',
	}

	CrossCompileFlags = {
		'x64' : 'ARCH_FLAGS=-m64',
		'x86' : 'ARCH_FLAGS=-m32',
	}

	def __init__(self, arch):
		try:
			canonical_host = Architecture.make_canonical( config.HOSTARCH )
		except KeyError:
			print("Unkown host architecture %s" % config.HOSTARCH, file=sys.stderr)
			sys.exit(1)

		if arch:
			try:
				arch = Architecture.make_canonical( arch )
			except KeyError:
				print("Unkown architecture %s" % arch, file=sys.stderr)
				sys.exit(1)

		if arch and arch != canonical_host:
			self.target = arch
			self.cross_compile = True
		else:
			self.target = canonical_host
			self.cross_compile = False


		try :
			self.flags = Architecture.CrossCompileFlags[self.target]
		except KeyError:
			print("Cross compilation not available for architecture %s" % self.target, file=sys.stderr)
			sys.exit(1)

		self.string = self.target

	def update(self):
		if not self.cross_compile:
			self.target = machine_default()
			self.string = self.target
			print("updated to %s" % self.target)

	def match(self, arch):
		return True if not arch else self.target == arch

	@classmethod
	def make_canonical(_, arch):
		return Architecture.KnownArchitectures[arch]


class Debug:
	def __init__(self, value):
		self.string = "debug" if value else "no debug"
		self.flags  = """DEBUG_FLAGS=%s""" % ("-debug -O0" if value else "-nodebug -O2")

class Install:
	def __init__(self, value):
		self.string = "installed" if value else "in-tree"
		self.flags  = """INSTALL_FLAGS=%s""" % ("" if value else "-in-tree")

class Timeouts:
	def __init__(self, ts, tg):
		self.single = Timeouts.check(ts)
		self.total  = Timeouts.check(tg)

	@classmethod
	def check(_, value):
		if value < 1:
			print("Timeouts must be at least 1 second", file=sys.stderr)
			sys.exit(1)

		return value

def init( options ):
	global arch
	global dry_run
	global generating
	global make
	global debug
	global install
	global timeout
	global output_width

	dry_run      = options.dry_run
	generating   = options.regenerate_expected
	make         = ['make']
	debug        = Debug(options.debug)
	install      = Install(options.install)
	arch         = Architecture(options.arch)
	timeout      = Timeouts(options.timeout, options.global_timeout)
	output_width = 24


def update_make_cmd(force, jobs):
	global make

	make = ['make'] if not force else ['make', "-j%i" % jobs]

def validate():
	errf = os.path.join(BUILDDIR, ".validate.err")
	make_ret, out = tools.make( ".validate", error_file = errf, output=subprocess.DEVNULL, error=subprocess.DEVNULL )
	if make_ret != 0:
		with open (errf, "r") as myfile:
			error=myfile.read()
		print("ERROR: Invalid configuration %s:%s" % (arch.string, debug.string), file=sys.stderr)
		print("       verify returned : \n%s" % error, file=sys.stderr)
		tools.rm(errf)
		sys.exit(1)

	tools.rm(errf)

def prep_output(tests):
	global output_width
	output_width = max(map(lambda t: len(t.target()), tests))
