import os
import sys
import sipconfig
import sipdistutils
import PyQt5
import subprocess
import argparse

from PyQt5.QtCore import PYQT_CONFIGURATION
from plio.utils.utils import find_in_dict
from PyQt5.QtCore import PYQT_CONFIGURATION as qtconfigdict
from sipconfig import ModuleMakefile


def commandOutput(cmd, arguments):
    '''
    Run a sub process and return output as string
    '''
    return subprocess.check_output([cmd] + arguments).strip().decode('utf-8')

def main (module):
    # The name of the SIP build file generated by SIP and used by the build
    # system.
    build_file = "bundle"+".sbf"
    target = module+".so"

    # Get the extra SIP flags needed by the imported qt module.  Note that
    # this normally only includes those flags (-x and -t) that relate to SIP's
    # versioning system.
    qt_sip_flags = qtconfigdict["sip_flags"]

    current_env_path = commandOutput("conda", ["info"])
    # search the output of conda info for the current environment path
    for item in current_env_path.split("\n"):
        if "default environment" in item:
            current_env_path = item.strip().split(' ')[3]

    sip_bin = current_env_path + "/bin/sip"
    pyqt_sip_dir = current_env_path + "/share/sip/PyQt5"

    # Get the PyQt configuration information.
    config = sipconfig.Configuration()

    # Run SIP to generate the code.  Note that we tell SIP where to find the qt
    # module's specification files using the -I flag.
    os.system(" ".join([sip_bin, "-c", ".", "-b", build_file, "-I",
        pyqt_sip_dir, qt_sip_flags, module+".sip"]))

    # We are going to install the SIP specification file for this module and
    # its configuration module.
    installs = []
    installs.append([module+".sip", os.path.join(pyqt_sip_dir, "isis3")])

    isis_root = os.getenv("ISISROOT")
    if not isis_root:
        raise("Please set ISIS")

    extra_cxxflags = ["$(ALLINCDIRS)"]
    extra_libs = ["$(ALLLIBS)"]
    extra_lib_dirs = ["$(ALLLIBDIRS)"]

    makefile = ModuleMakefile(configuration=config, build_file=build_file, installs=installs)
    makefile.extra_cxxflags = extra_cxxflags
    makefile.extra_lflags = extra_lib_dirs
    makefile.generate()

    # add import line for isismake.os
    isis_makefile = "include " + isis_root + "/make/isismake.os"

    with open("Makefile", 'r+') as f:
        content = f.read()
        content = content.replace("LIBS =", "LIBS = " + ' '.join(extra_libs))
        f.seek(0, 0)
        f.write(isis_makefile + '\n\n' + content)

if __name__ == "__main__":
    parser = argparse.ArgumentParser()
    parser.add_argument('module', action='store', help='The name of the python module to generate from C++')
    args = parser.parse_args()
    main(args.module)
