"""Tools to handle malformed las/laz files"""

# https://gis.stackexchange.com/questions/413191/python-pdal-error-reading-format-1-4-las-file-readers-las-error-global-enco

import argparse
import logging
import os
import shutil
import tempfile


def unlock_file(finename: str):
    f = open(finename, "rb+")
    f.seek(6)
    f.write(bytes([17, 0, 0, 0]))
    f.close()


def copy_and_hack_input_file(in_file: str, out_file: str):
    print(f"Gestion de l'erreur en créeant un nouveau LAZ que l'on modifiera : {in_file}")
    shutil.copy(in_file, out_file)
    unlock_file(out_file)
    print(f"Patch appliqué sur :  {out_file}")


def copy_and_hack_decorator(func):
    """Decorator function to copy and hack a malformed las/laz file that generates this error
    when reading with PDAL
    "readers.las: Global encoding WKT flag not set for point format 6 - 10."

    CAUTION: The decorated function must have the path to a las/laz input file as its first argument
    """

    def newfn(*args, **kwargs):
        try:
            return func(*args, **kwargs)
        except RuntimeError as e:
            logging.debug(f"Caught RuntimeError: {e}")
            if "readers.las: Global encoding WKT flag not set for point format 6 - 10." in str(e):
                args = list(args)
                in_file = args[0]
                with tempfile.NamedTemporaryFile(suffix=os.path.splitext(in_file)[-1]) as tmp:
                    copy_and_hack_input_file(in_file, tmp.name)
                    args[0] = tmp.name

                    return func(*args, **kwargs)

            else:
                raise e

    return newfn


def parse_args():
    parser = argparse.ArgumentParser("Unlock las/laz files generated by TerraSolid (it overwrites the input)")
    parser.add_argument("--input", "-i", type=str, required=True, help="Input file")

    return parser.parse_args()


if __name__ == "__main__":
    args = parse_args()
    unlock_file(args.input)
