import os

from pybin.tools import *

import pybin.settings
import datetime

from string import Template

class DeltaTemplate(Template):
    delimiter = "%"

def strfdelta(tdelta, fmt):
    d["H"], rem = divmod(tdelta.seconds, 3600)
    d["M"], d["S"] = divmod(rem, 60)
    t = DeltaTemplate(fmt)
    return t.substitute(**d)

# Test class that defines what a test is
class Test:
	def __init__(self):
		self.name = ''
		self.path = ''
		self.arch = ''

	def toString(self):
		return "{:25s} ({:5s} {:s})".format( self.name, self.arch if self.arch else "Any", self.target() )

	def prepare(self):
		sh("mkdir -p %s" % os.path.join(self.path, '.err'))
		sh("mkdir -p %s" % os.path.join(self.path, '.out'))
		sh("mkdir -p %s" % os.path.join(self.path, '.in' ))

	def expect(self):
		return ("%s/.expect/%s%s.txt" % (self.path, self.name, '' if not self.arch else ".%s" % self.arch))

	def error_log(self):
		return ("%s/.err/%s.log"    % (self.path, self.name))

	def output_log(self):
		return ("%s/.out/%s.log"    % (self.path, self.name))

	def input(self):
		return ("%s/.in/%s.txt"     % (self.path, self.name))

	def target_output(self):
		return self.output_log() if not settings.generating else self.expect()

	def target(self):
		return os.path.join(self.path, self.name)

	@classmethod
	def valid_name(_, name):
		return not name.endswith( ('.c', '.cc', '.cpp', '.cfa') )

	@classmethod
	def from_target(_, target):
		test = Test()
		test.name = os.path.basename(target)
		test.path = os.path.dirname (target)
		test.arch = settings.arch.toString() if settings.arch.cross_compile else ''
		return test


class TestResult:
	SUCCESS = 0
	FAILURE = 1
	TIMEOUT = 124

	@classmethod
	def toString( cls, retcode, duration ):
		if settings.generating :
			if   retcode == TestResult.SUCCESS: 	text = "Done   "
			elif retcode == TestResult.TIMEOUT: 	text = "TIMEOUT"
			else :						text = "ERROR code %d" % retcode
		else :
			if   retcode == TestResult.SUCCESS: 	text = "PASSED "
			elif retcode == TestResult.TIMEOUT: 	text = "TIMEOUT"
			else :						text = "FAILED with code %d" % retcode

		text += "    C%s - R%s" % (cls.fmtDur(duration[0]), cls.fmtDur(duration[1]))
		return text

	@classmethod
	def fmtDur( cls, duration ):
		if duration :
			hours, rem = divmod(duration, 3600)
			minutes, rem = divmod(rem, 60)
			seconds, millis = divmod(rem, 1)
			return "%2d:%02d.%03d" % (minutes, seconds, millis * 1000)
		return " n/a"