"""
MIT License

Copyright (c) 2023 RWTH Aachen University

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
"""
from numpy import empty
import pytest
import sys
from itertools import chain
import argparse
import os

#### USAGE OF THIS SCRIPT #####
# This script calls the unit_tests found in 'unit_tests/'
# If called with no arguments, all tests found in the test path will be executed,
# which is also the default option if the arguments are invalid.
# A short test-summary is displayed at the end listing failures and errors (-rfE).

# Arguments: List of markers
# - structure of list: Marker connector marker connector ... marker
#   - marker = valid marker
#   - connector = "and" or "or"
# - behavior of the list: The connectors define the connections between the markers
#   e.g.: "ErrorEstimator and getter" calls all test-functions that are marked with "ErrorEstimator" and "getter"
#   (i.e. all "getter"-funcs within the ErrorEstimator test module)
#   e.g.: "ErrorEstimator or getter" calls all test-functions marked with either "ErrorEstimator" or "getter"
#   (i.e. the complete ErrorEstimator test module and all "getter"-functions in the other modules)

# Note: If new markers are added in pytest.ini, these should also be added here in marker_list

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

TEST_PATH = os.path.dirname(__file__)
DEFAULT_OPTIONS = "-rfE"

### Marker options
marker_list = ["init_func", "getter", "setter", "output", "functionality", \
    "ErrorEstimator", "Aggregator"]

### Marker list in lower_case for comparison
marker_compare_list = [elem.lower() for elem in marker_list]


### checks the provided list of markers for validity (independent of upper-/lowercase)
def choose_markers(marker):
    chosen_markers = []

    # every second element of the provided marker list should be either "and" or "or" (called connector)
    if len(marker) > 1 :
        for ele in marker[1::2]:
            if ele.lower() not in ["and", "or"]:
                print("Warning: The list of markers should have following form: Marker connector marker connector ... marker")
                print("At this: Marker = valid marker, connector = \"and\" or \"or\"")
                print("Warning: Pytest will be run without markers.")
                return []

    # list should end with a marker not with a connector
    if len(marker) % 2 == 0:
        del marker[-1]

    # check whether the provided markers are valid (independent of upper-/lowercase)
    all_indices = []
    for elem in marker[0::2]:
        indices  = [index for (index, item) in enumerate(marker_compare_list) if item == elem.lower()]
        if not indices:
            print("Warning: \"{}\" is not a valid marker.")
            print("Warning: Pytest will be run without markers.")
            return []
        all_indices.extend(indices)

    # create valid list with the correct spelling of the marker
    chosen_markers = [marker_list[all_indices[int(i/2)]] if (i % 2) == 0 else marker[i].lower() for i in range(len(marker))]

    # convert list to string
    chosen_markers = "-m " + ' '.join(chosen_markers)

    return chosen_markers

### Calls pytest with the chosen arguments
def test(cmd):
    cmd += [TEST_PATH]
    print("Running: Pytest {}".format(' '.join(cmd)))
    return pytest.main(cmd)


if __name__ == "__main__":

    #a list of markers can be provided with the function call
    parser = argparse.ArgumentParser()
    parser.add_argument('-m', '--marker', action="store_true", dest="markers",
                    help="run only tests with specific markers", default=False)
    parser.add_argument('text', action='store', type=str, nargs='*', help='The text to parse.')
    options = parser.parse_args()

    #call pytest depending on the chosen arguments
    if options.markers:         #marker shall be used
        if options.text:
            chosen_markers = choose_markers(options.text)
            if chosen_markers:
                test([DEFAULT_OPTIONS, chosen_markers])
            else:
                test([DEFAULT_OPTIONS])  #no valid markerlist provided
        else:
            test([DEFAULT_OPTIONS])      #no markerlist provided

    else:
        test([DEFAULT_OPTIONS])          #default call if no markers shall be used