#!/usr/bin/env python3
# -*- coding: utf-8 -*-

# Copyright (c) 2016 France-IOI, MIT license
#
# http://opensource.org/licenses/MIT

# This tool select a minimal set of tests finding errors in each solution.


import argparse, glob, json, os, shutil, subprocess, sys

SELFDIR = os.path.normpath(os.path.dirname(os.path.abspath(__file__)))

CFG_TASKGRADER = os.path.join(SELFDIR, '../../', 'taskgrader.py')


def checkData(args, data):
    """Check integrity of data."""
    # Remove testCases and solutions which don't exist anymore
    testCasesNames = []
    for case in data['testCases'][:]:
        if case.get('path', None) and not os.path.isfile(os.path.join(args.taskpath, case['path'])):
            print("Removing old test case '%s'." % case['name'])
            data['testCases'].remove(case)
        else:
            testCasesNames.append(case['name'])

    solutionNames = []
    for solution in data['solutions'][:]:
        if solution.get('path', None) and not os.path.isfile(os.path.join(args.taskpath, solution['path'])):
            print("Removing old solution '%s'." % solution['name'])
            data['solutions'].remove(solution)
        else:
            solutionNames.append(solution['name'])

    # Remove coverage for pairs which aren't here anymore
    for covSolKey in list(data['coverage'].keys()):
        if covSolKey in solutionNames:
            for covTestKey in list(data['coverage'][covSolKey].keys()):
                if covTestKey not in testCasesNames:
                    del data['coverage'][covSolKey][covTestKey]
        else:
            del data['coverage'][covSolKey]

    # Remove selected tests which aren't in the data anymore
    data['selected'] = list(filter(lambda c: c in testCasesNames, data['selected']))

    return data

def loadData(args):
    """Load testSelect data from the task."""
    # Load testSelect.json
    try:
        data = json.load(open(os.path.join(args.taskpath, 'testSelect.json')))