#!/usr/bin/env python3

import os
import sys
import subprocess
from io import open

PYTHON_VERSIONS = ["3"]

"""
This test uses sys.stdout.
That means this test doesn't verify:
    - file output process
    - differences from sys.stdout like line terminater
"""

def compare(case, arguments=[]):
    failed = False
    for pyver in PYTHON_VERSIONS:
        ext = "xlsx"
        if os.path.exists("test/%s.xlsm" % case):
            ext = "xlsm"

        if os.name == 'posix':# in case of Linux
            command = ["python%s" %pyver]
        elif os.name == 'nt':# in case of Windows
            # Use py.exe http://blog.python.org/2011/07/python-launcher-for-windows_11.html on Windows
            command = ["py", "-%s" %pyver] 
        else:
            print("os.name is unexpected: "+os.name)
            sys.exit(1)
        left = subprocess.check_output(command + ["./xlsx2csv.py"] + arguments + ["test/%s.%s" %(case, ext)]).decode('utf-8').replace('\r','')

        f = open("test/%s.csv" %case, "r", encoding="utf-8", newline="")
        right = f.read().replace('\r','')
        f.close()

        if left != right:
            print("FAILED: %s %s" %(case, pyver))
            print(" actual:", left.replace("\r", "\\r").replace("\n", "\\n"))
            print(" expected:", right.replace("\r", "\\r").replace("\n", "\\n"))
            failed = True
        else:
            print("OK: %s %s" %(case, pyver))

        # test STDIN, only works for python3
        if pyver == "2":
            continue

        xfile = open("test/%s.%s" %(case,ext), "rb")
        stdin = xfile.read()
        xfile.close()

        pipe = subprocess.run(command + ["./xlsx2csv.py"] + arguments + ["-"], input = stdin, capture_output = True)
        stdinleft = pipe.stdout.decode("utf-8").replace('\r','').replace('\r','')

        if stdinleft != right:
            print("FAILED (STDIN): %s %s" %(case, pyver))
            failed = True
        else:
            print("OK (STDIN): %s %s" %(case, pyver))

    if failed:
        sys.exit(1)


compare("datetime", ["--dateformat=%Y-%m-%d %H:%M:%S"])
compare("empty_row")
compare("junk-small")
compare("last-column-empty")
compare("sheets", ["-a"])
subprocess.check_call([sys.executable, "test/test_invalid_sheet_output.py"])
compare("skip_empty_lines", ["-i"])
compare("twolettercolumns")
compare("xlsx2csv-test-file")
compare("escape", ["-e"])
compare("hyperlinks", ["--hyperlinks"])
compare("hyperlinks_continous", ["--hyperlinks"])
compare("namespace")
compare("float")
compare("variousdelim", ["--all","--sheetdelimiter=x33", "--lineterminator=\\r", "--delimiter=\\t"])
compare("utf8")
compare("no_cell_ids")
compare("sheets_order", ["-a"])
compare("formatted_inline_string")
subprocess.check_call([sys.executable, "test/test_inline_phonetics.py"])
subprocess.check_call([sys.executable, "test/test_styles.py"])
compare("float_formatting", ["--floatformat=%f"])
compare("float_formatting_custom0", ["--floatformat=%.0f"])
compare("float_formatting_custom2", ["--floatformat=%.2f"])
compare("percentage")
compare("percentage_ignore", ["--ignore-percentage"])
compare("shared_string_oob")
compare("quoted_literals")
compare("date1904_0")
compare("date1904_1")
compare("hidden_rows")
compare("date1900")
compare("date1900", ["--dateformat=%Y-%m-%d %H:%M:%S"])


def test_dir_sheetname():
    # --sheetname must apply to directory input too, including nested folders (#320)
    import shutil, tempfile
    cmd = [sys.executable, "./xlsx2csv.py", "-n", "e"]
    expected = subprocess.check_output(cmd + ["test/sheets_order.xlsx"])
    tmp = tempfile.mkdtemp()
    try:
        os.mkdir(os.path.join(tmp, "nested"))
        shutil.copy("test/sheets_order.xlsx", os.path.join(tmp, "a.xlsx"))
        shutil.copy("test/sheets_order.xlsx", os.path.join(tmp, "nested", "b.xlsx"))
        subprocess.check_output(cmd + [tmp])
        for out in (os.path.join(tmp, "a.csv"), os.path.join(tmp, "nested", "b.csv")):
            f = open(out, "rb")
            actual = f.read()
            f.close()
            if actual != expected:
                print("FAILED: dir_sheetname %s" % out)
                sys.exit(1)
    finally:
        shutil.rmtree(tmp)
    print("OK: dir_sheetname")

test_dir_sheetname()
