import os
from setuptools import setup
from setuptools.command.develop import develop
from setuptools.command.install import install

DS9CADET_text = """CADET
*
menu
DS9CADET CADET -x $xpa_method  $param(CADET); -dec $decompose -shift $shift -th1 $threshold1 -th2 $threshold2  | $text
#DS9CADET CADET -x $xpa_method  $param(CADET); -dec $decompose -shift $shift -b $bootstrap -n $boot_n -th1 $threshold1 -th2 $threshold2  | $text

param CADET
shift checkbox {Shift} 0 {Shift the input region by +/- 1 pixel (increases execution time 8 times).}
# bootstrap checkbox {Bootstrap} 0 {Boostrap individual counts of the input image (increases execution time N times).}
# boot_n entry {Bootstrap N} 1 {Number of bootstrap iterations per single rotation-shifting configuration.}
decompose checkbox {Decompose} 1 {Decompose raw cavity prediction into individual cavities.}
threshold1 entry {Threshold1} 0.5 {Volume calibrating threshold (only applied if Decompose).}
threshold2 entry {Threshold2} 0.9 {TP/FP calibrating threshold (only applied if Decompose).}
endparam
"""

def ReplaceStringInFile(path, string1, string2, path2=None):
    """Replaces string in a txt file"""
    fin = open(path, "rt")
    data = fin.read()
    data = data.replace(string1, string2)
    fin.close()
    if path2 is not None:
        path = path2
        if os.path.exists(path):
            os.remove(path)
        fin = open(path, "x")
    else:
        fin = open(path, "wt")
    fin.write(data)
    fin.close()
    return

def LoadDS9CADET():
    """Load the plugin in DS9 parameter file
    """

    ds9 = os.popen("whereis ds9").read()

    if ds9 != "":
        home = os.environ["HOME"]
        DS9CADET_path = f"{home}/.ds9/DS9CADET.ds9.ans"

        os.system(f"mkdir -p {home}/.ds9")

        with open(DS9CADET_path, "w") as f:
            f.write(DS9CADET_text)

        version = os.popen("ds9 -version").read().replace("\n", "").replace("ds9 ", "")
        pref = f"{home}/.ds9/ds9.{version}.prf"

        if os.path.isfile(pref):
            print("DS9 parameter file found")
            print(pref)
            ReplaceStringInFile(path=pref, string1="user4 {}", string2="user4 {%s}" % (DS9CADET_path))
        else:
            print("DS9 parameter file not found. Creating new one.")
            with open(pref, "w") as f:
                f.write("global panalysis\narray set panalysis { user2 {} autoload 1 user3 {} log 0 user4 {} user " + DS9CADET_path + " }")
            os.chmod(pref, 0o644)
    else:
        print("DS9 not found. If you want to use CADET as DS9 plugin, please install DS9 first.")

class PostDevelopCommand(develop):
    """Post-installation for development mode."""
    def run(self):
        develop.run(self)
        LoadDS9CADET()

class PostInstallCommand(install):
    """Post-installation for installation mode."""
    def run(self):
        install.run(self)
        LoadDS9CADET()

setup(
    cmdclass={
        "install": PostInstallCommand,
        "develop": PostDevelopCommand
    },
)
