#!/usr/bin/env python
# -*- coding: utf-8 -*-

"""
NX Client for Windows installer
Checks whether NX Client for Windows is installed in the system, the
classes used for this process are used for other operations too.
"""

import os
import argparse
import subprocess
import time
import windowsclasses


def parse_arguments():
    """
    Argument parser, based on argparse module

    Keyword arguments:
    @return args -- arguments given by console
    """
    parser = argparse.ArgumentParser()
    if windowsclasses.DecideArchitecture.Is64Windows():
        local_default = (windowsclasses.DecideArchitecture.GetProgramFiles64()
                         + "\\CIRCLE\\")
    else:
        local_default = (windowsclasses.DecideArchitecture.GetProgramFiles32()
                         + "\\CIRCLE\\")
    if (not os.path.exists(local_default[:-1])
            and os.path.exists(os.environ['APPDATA']+"\\CIRCLE")):
        local_default = os.environ['APPDATA']+"\\CIRCLE\\"
    parser.add_argument(
        "-l", "--location",
        help="Location of the client files in the system",
        default=local_default)
    args = parser.parse_args()
    return args


def main():
    try:
        nx_install_location = None
        while nx_install_location is None:
            print "Checking whether NX Client for Windows is installed"
            handler = windowsclasses.RegistryHandler()
            try:
                nx_install_location = handler.get_key_value(
                    "SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\"
                    + "Uninstall\\nxclient_is1",
                    "InstallLocation", "key")
                print ("NX Client for Windows is found at "
                       "'%s'" % nx_install_location)
                process = subprocess.Popen(
                    "%s\\nxclient.exe" % nx_install_location)
                time.sleep(2)
                process.terminate()
            except:
                print "NX Client for Windows isn't installed on the system."
                print "\tCommencing the install"
                subprocess.Popen(os.path.dirname(
                    os.path.realpath(__file__))
                    + "\\nxclient-3.5.0-9.exe").wait()
    except:
        pass

if __name__ == "__main__":
    main()