#!/usr/bin/python3

#	control++ : System configuration tool
#	Copyright (C) 2017-2021 Alexey Appolonov
#
#	This program is free software: you can redistribute it and/or modify
#	it under the terms of the GNU General Public License as published by
#	the Free Software Foundation, either version 3 of the License, or
#	(at your option) any later version.
#
#	This program is distributed in the hope that it will be useful,
#	but WITHOUT ANY WARRANTY; without even the implied warranty of
#	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#	GNU General Public License for more details.
#
#	You should have received a copy of the GNU General Public License
#	along with this program.  If not, see <http://www.gnu.org/licenses/>.

# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #

import os
import argparse
import subprocess
from common       import MODES, Const
from ax.printer   import Printer

# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
# Parsing the arguments

TARGETS = ['bl', 'wl', 'all']

argparser = argparse.ArgumentParser()
argparser.add_argument(
	'-t', '--targets',
	metavar='TYPE_OF_LIST', type=str, nargs='+',
	choices=TARGETS, required=True,
	help=f'Targets of the testing ({" | ".join(TARGETS)})',
	)
argparser.add_argument(
	'-m', '--mode',
	metavar='MODE', type=str,
	choices=MODES, required=True,
	help=f'Execution mode ({" | ".join(MODES)})',
	)
args = argparser.parse_args()

if 'all' in args.targets:
	args.targets = TARGETS[:-1]

# Initialize a namespace containing string constants
const = Const(args.mode)

BW_LIST_FILE_NAME = 'bw-list-modesetting'
BW_LIST_FILE_PATH = os.path.join(const.EXEC_DIR, BW_LIST_FILE_NAME)
BW_LIST_MODESETTING = [BW_LIST_FILE_PATH, '--indent', '--list']

# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
# Initialising the printer

printer = Printer(plain=True, silent=False, block_printing=False)

# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #

if __name__ == '__main__':

	command = []
	success = 0

	# Running the tests
	for i, target in enumerate(args.targets):
		command = BW_LIST_MODESETTING + \
			(['black'] if target == 'bl' else ['white']) + \
			(['--clear'] if i == (len(args.targets) - 1) else []) + \
			['--mode', args.mode]
		printer.Div()
		printer.LineBegin("Running '" + ' '.join(command) + "'")
		printer.LineEnd('[IN PROGRESS]')
		res = subprocess.run(command)
		printer.LineRestart()
		if res.returncode == 0:
			printer.LineEnd('[V]')
			success += 1
		else:
			printer.LineEnd('[X]')

	# Summarizing
	print(success, 'of', len(args.targets), 'tests have succeeded.')

	exit(0 if success == len(args.targets) else 1)
