#!/usr/bin/env python3

"""
Displays the names of all the files in which the provider/subroutine/function
given as argument is used. With the -r flag, the name can be changed in the
whole quantum package.

Usage:
    qp_name <name> [-r <new_name> | --rename=<new_name>]

Options:
    -h                                  Prints the help message
    -r <new_name> --rename=<new_name>   Renames the provider /
                                        subroutine / function and all
                                        its occurences

Note:
    It is safe to create a commit before renaming a provider, and then to
    check what has changed using git diff.

"""


import re
import sys
import os


try:
    from docopt import docopt
    from qp_path import QP_SRC, QP_ROOT
except ImportError:
    print("source quantum_package.rc")
    raise


def main(arguments):
    """Main function"""

    # Check that name exist in */IRPF90_man
    print("Checking that name exists...")
    all_modules = os.listdir(QP_SRC)

    f = arguments["<name>"]+".l"
    found = False
    for mod in all_modules:
        if os.path.isdir(os.path.join(QP_SRC, mod, "IRPF90_man")):
            for filename in os.listdir(os.path.join(QP_SRC, mod, "IRPF90_man")):
                if filename == f:
                    found = True
                    break
        if found: break

    if not found:
        print("Error:")
        print("The variable/subroutine/function \""+arguments["<name>"] \
        + "\" was not found in the sources.")
        print("Did you compile the code at the root?")
        print("Continue? [y/N]  ", end=' ')
        cont = sys.stdin.read(1).strip() in ["y", "Y"]
        if not cont:
            print("Aborted")
            sys.exit(1)

    # Now search in all the files
    if arguments["--rename"]:
        print("Replacing...")
    else:
        print("Searching...")

    name = re.compile(r"\b"+arguments["<name>"]+r"\b", re.IGNORECASE)

    for mod in all_modules:
        dirname = os.path.join(QP_SRC, mod)
        if not os.path.isdir(dirname):
            continue

        for filename in os.listdir(dirname):
            if "." not in filename:
                continue
            filename = os.path.join(dirname, filename)
            if not os.path.isfile(filename):
                continue
            with open(filename, "r") as f:
                f_in = f.read()
            if name.search(f_in):
                print(filename)
                if arguments["--rename"]:
                    f_new = name.sub(arguments["--rename"], f_in)
                    with open(filename, "w") as f:
                        f.write(f_new)

    print("Done")
    with open(os.path.join(QP_ROOT, "REPLACE"), 'a') as f:
        print("qp_name "+" ".join(sys.argv[1:]), file=f)





if __name__ == '__main__':
    ARGS = docopt(__doc__)
    main(ARGS)

