import os
import sys
import saxonc


def try_to_string(proc):
    xsltproc = proc.new_xslt_processor()
    xsltproc.set_parameter("before", proc.make_string_value("two"))
    xsltproc.set_parameter("after", proc.make_string_value("duece"))
    result = xsltproc.transform_to_string(source_file="try_saxon_input.xml",
                                          stylesheet_file="try_saxon.xsl")
    return bool({'duece' in result})


def try_to_file(proc, proc_type=None):
    output_filename = "try_saxon_output.xml"

    if os.path.isfile(output_filename):
        os.remove(output_filename)

    if proc_type == "3.0":
        # WORKS
        xsltproc = proc.new_xslt30_processor()
    else:
        # DOES NOT WORK (No file output. No error message.)
        xsltproc = proc.new_xslt_processor()

    xsltproc.set_parameter("before", proc.make_string_value("two"))
    xsltproc.set_parameter("after", proc.make_string_value("duece"))
    xsltproc.set_cwd(os.getcwd())
    xsltproc.transform_to_file(source_file="try_saxon_input.xml",
                               stylesheet_file="try_saxon.xsl",
                               output_file=output_filename)
    try:
        with open(output_filename) as output_file:
            return bool({'duece' in output_file})
    except FileNotFoundError:
        return False


def main():
    with saxonc.PySaxonProcessor(license=False) as proc:
        print(f"Processor version: {proc.version}")
        print(f"Did try_to_string() work? - {try_to_string(proc)}")
        print(f"Did try_to_file() work? - {try_to_file(proc)}")
        print(f"Did try_to_file() (3.0) work? - {try_to_file(proc, '3.0')}")


if __name__ == '__main__':
    sys.exit(main())
