#!/usr/bin/env python3
# -*- coding: utf8 -*-
# test encoding: à-é-è-ô-ï-€

# Copyright 2020 University of Liège
# 
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# 
#     http://www.apache.org/licenses/LICENSE-2.0
# 
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.


#
# runs a test as if it was installed
#   - fixes the python path in a dev environment
#   - creates a workspace folder


class DupStream:
    def __init__(self, stream1, stream2):
        self.stream1 = stream1
        self.stream2 = stream2

    def write(self, data):
        self.stream1.write(data)
        self.stream2.write(data)

    def flush(self):
        self.stream1.flush()
        self.stream2.flush()


class Tee:
    def __init__(self, name):
        import sys
        self.file = open(name, 'w')
        self.stdoutbak = sys.stdout
        self.stderrbak = sys.stderr
        sys.stdout = DupStream(sys.stdout, self.file)
        sys.stderr = DupStream(sys.stderr, self.file)

    def __del__(self):
        import sys
        sys.stdout = self.stdoutbak
        sys.stderr = self.stderrbak
        self.file.close()


def main(thisfile):
    global __file__   # required for run_pfem.py
    global __name__   # required for run_pfem.py
    import sys, os
    # adds "." to the pythonpath
    sys.path.append(os.path.dirname(os.path.realpath(__file__)))
    import fwk.wutils as wu
    from fwk.coloring import ccolors
    import fwk.testing # [AC]tmp fix for win-msys, to be removed once we understand why python cannot import this module outside run.py

    # redirect C++ streams to Python
    import fwk
    redirect = fwk.StdOutErr2Py()

    # parse args
    args = wu.parseargs()
    if args.fpe:
        fwk.enableFpe() # enables floating point exceptions at runtime
        print(ccolors.ANSI_YELLOW + 'Floating point exceptions will cause numpy to overflow!' + ccolors.ANSI_RESET)

    # run all tests sequentially
    for testname in args.file:
        testname = os.path.abspath(testname)
        if not os.path.isfile(testname):
            raise Exception("file not found: %s" % testname)

        wu.setupwdir(testname)

        __file__ = testname
        __name__ = "__main__"
        print("[run.py] __file__", __file__)
        # split streams
        tee = Tee('stdout.txt')

        # start test
        import time, socket
        print('-' * 80)
        print(ccolors.ANSI_BLUE + 'PyStarting...' + ccolors.ANSI_RESET)
        print("starting test", testname)
        print("time:", time.strftime("%c"))
        print("hostname:", socket.gethostname())
        exec(open(testname, 'r', encoding='utf8').read(), globals(), globals()) # exec at global level!!

if __name__ == "__main__":
    main(__file__)