#!/usr/bin/python3

import dogtail.tc
from dogtail.procedural import *
from dogtail.utils import run
from dogtail.predicate import GenericPredicate
import os
import time
import traceback
os.environ['LANG'] = 'en_US.UTF-8'

class NotFound(Exception):
	pass

def find(*a, **ka):
	"Find a widget in the current window by name (and index, if there's more than one."
	if 'idx' in ka:
		idx = ka.pop('idx')
	else:
		idx = None
	window = tree.root.application('openmsx-catapult')
	targets = window.findChildren(GenericPredicate(*a, **ka))
	if idx is None:
		idx = 0
		if len(targets) > 1:
			print('Warning: multiple elements with name "%s" were found' % name, file = sys.stderr)
	if len(targets) <= idx:
		raise NotFound('not found')
	return targets[idx]

def start():
	'Start the application and focus the window. If the configuration chooser pops up, dismiss it.'
	run('openmsx-catapult')
	
	try:
		find('Check for working hardware configurations after closing this dialog').click()
		find('OK').click()
	except:
		pass

	# Wait for main window to open.
	time.sleep(2)

	focus.application('openmsx-catapult')

def test_detect():
	'Run machine detection, the quit.'
	start()

	find('File').click()
	find('Test MSX Hardware').click()

	#focus.widget.findByPredicate(GenericPredicate(name = 'Checking openMSX configurations'))
	for i in range(600):
		try:
			done = find('Done', idx = 1)
			break
		except NotFound:
			time.sleep(1)
	done.click()

	find('File').click()
	find('Quit').click()

def test_run_msx():
	'Start the emulator.'
	start()
	find('Start').click()
	time.sleep(3)
	# Check that a Stop button has appeared.
	find('Stop')
	marker = 'autopkgtest is sending bytes'
	os.system(r"xvkbd -xsendevent -window 'openMSX 1*' -text '\D1\{F10}puts stderr \"\\n" + marker + r"\\n\"\r\D3quit\r'")
	time.sleep(3)
	# Check that there is a start button again.
	find('Start')
	messages = find(description = 'Info, warning and error messages')
	# Find the output that should have been sent.
	assert marker in messages.text.split('\n')
	find('File').click()
	find('Quit').click()

test_detect()
test_run_msx()
