# -*- coding: utf-8 -*-
from setuphelpers import *


def install():
    # Declaring local variables
    bin_name = glob.glob("ImageMagick-*.exe")[0]
    version = control.get_software_version()
    version_key = ".".join([version.split(".")[0], version.split(".")[1], version.split(".")[2]])

    # Save old settings
    for soft in installed_softwares("ImageMagick"):
        install_location = soft["install_location"]

        for xml in glob.glob(makepath(install_location, "*.xml")):
            filecopyto(xml, basedir)
            remove_file(xml)

        for rdf in glob.glob(makepath(install_location, "*.rdf")):
            filecopyto(rdf, basedir)
            remove_file(rdf)

        for icc in glob.glob(makepath(install_location, "*.icc")):
            filecopyto(icc, basedir)
            remove_file(icc)

    # uninstall previous version
    for soft in installed_softwares("ImageMagick"):
        if soft["version"] < version:
            print("Uninstalling previous version: %s" % soft["name"])
            run(uninstall_cmd(soft["key"]))
            wait_uninstallkey_absent(soft["key"])

    # Installing the software
    install_exe_if_needed(
        bin_name,
        silentflags="/VERYSILENT /NORESTART",
        key="ImageMagick %s Q16-HDRI (64-bit)_is1" % version_key,
        min_version=version,
    )
    for soft in installed_softwares("ImageMagick"):
        new_install_location = soft["install_location"]

    # Restore old settings
    for xml in glob.glob(makepath(basedir, "*.xml")):
        filecopyto(xml, new_install_location)

    for rdf in glob.glob(makepath(basedir, "*.rdf")):
        filecopyto(rdf, new_install_location)

    for icc in glob.glob(makepath(basedir, "*.icc")):
        filecopyto(icc, new_install_location)
