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

##
# Windows icon installer for CIRCLE client application
##

import os, sys, argparse, subprocess
if sys.hexversion > 0x02070000:
    from collections import *
else:
    from OrderedDict import *
import pythoncom
from win32com.shell import shell, shellcon
from nx_client_installer import DecideArchitecture, RegistryHandler, Struct

##
# Argument parser, based on argparse module
# @return args
#
def pars_arguments():
    parser = argparse.ArgumentParser();
    parser.add_argument("-d", "--driver", help="Select webdriver. Aside from Firefox, you have to install first the proper driver.", \
        type=str, choices=['firefox', 'chrome', 'iexplore', 'opera'], default="firefox", required=False)
    if DecideArchitecture.Is64Windows():
        local_default = DecideArchitecture.GetProgramFiles64()+"\\CIRCLE\\"
    else:
        local_default = 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, required=False)
    parser.add_argument("-r", "--remove", help="Remove installed files instead of creating them", action="store_true", required=False)
    parser.add_argument("-u", "--url", help="Whether we installed and we want to use selenium or not", action="store_true", required=False)
    parser.add_argument("-t", "--target", help="If this is an URL icon, where should it point", default="https://pc3.szgt.uni-miskolc.hu/", required=False)
    args = parser.parse_args();
    return args
    
##
# Custom protocol register based on RegistryHandler module
#   Can raise AttributeError on wrongly provided dictionary chain
# @param dict_chain OrderedDictionary chain of the registry tree
#
def custom_protocol_register(custom_protocol):
    if not isinstance(custom_protocol, OrderedDict):
        raise AttributeError
    print "\t"+custom_protocol.iterkeys().next()
    try:
        custom_arguments = Struct()
        custom_arguments.registry = "HKCR"
        handler = RegistryHandler(custom_arguments)
        handler.create_registry_from_dict_chain(custom_protocol, True)
        print "\t\tDone!"
    except:
        raise
    
##
# Main program
#   read the parameters
#   create a proper icon with the proper driver
#   call the nx_client_installer
def main():
    #try:
        args = pars_arguments()
        shortcut = pythoncom.CoCreateInstance (
        shell.CLSID_ShellLink,
            None,
            pythoncom.CLSCTX_INPROC_SERVER,
            shell.IID_IShellLink
        )
        desktop_path = shell.SHGetFolderPath (0, shellcon.CSIDL_DESKTOP, 0, 0)
        if args.remove:
            location =os.path.join(desktop_path, "Cloud GUI")
            if os.path.isfile("%s%s" % (location, ".lnk")):
                os.remove("%s%s" % (location, ".lnk"))
            if os.path.isfile("%s%s" % (location, ".url")):
                os.remove("%s%s" % (location, ".url"))
        else:
            subprocess.call("python "+os.path.dirname(os.path.realpath(__file__))+"\\nx_client_installer.py")
            if args.url:
                location = os.path.join(desktop_path, "Cloud GUI.url")
                shortcut = file(location, 'w')
                shortcut.write('[InternetShortcut]\n')
                shortcut.write('URL='+args.target)
                shortcut.close()
            else:
                shortcut.SetPath (args.location+"cloud.py")
                if args.driver == "chrome":
                    shortcut.SetArguments("-d chrome")
                elif args.driver == "iexplore":
                    shortcut.SetArguments("-d ie")
                elif args.driver == "opera":
                    shortcut.SetArguments("-d opera")
                shortcut.SetDescription ("Tool to use CIRCLE Cloud")
                shortcut.SetIconLocation (args.location+"cloud.ico", 0)
                desktop_path = shell.SHGetFolderPath (0, shellcon.CSIDL_DESKTOP, 0, 0)
                persist_file = shortcut.QueryInterface (pythoncom.IID_IPersistFile)
                persist_file.Save (os.path.join (desktop_path, "Cloud GUI.lnk"), 0)
            print "Icon successfully created on desktop"
            print "Creating custom URL protocol handlers"
            try:
                custom_ssh = OrderedDict([('ssh', "URL:CIRCLE-SSH Protocol"), ('ssh\\URL Protocol', ""),\
                        ('ssh\\DefaultIcon', args.location+"cloud.ico"),\
                        ('ssh\\shell', {'open': {'command': "\"python.exe\" \""+args.location+"cloud.py\" \"%1\""}})])
                custom_protocol_register(custom_ssh)
                custom_rdp = OrderedDict([('rdp', "URL:CIRCLE-RDP Protocol"), ('rdp\\URL Protocol', ""),\
                        ('rdp\\DefaultIcon', args.location+"cloud.ico"),\
                        ('rdp\\shell', {'open': {'command': "\"python.exe\" \""+args.location+"cloud.py\" \"%1\""}})])
                custom_protocol_register(custom_rdp)
                custom_nx = OrderedDict([('nx', "URL:CIRCLE-NX Protocol"), ('nx\\URL Protocol', ""),\
                        ('nx\\DefaultIcon', args.location+"cloud.ico"),\
                        ('nx\\shell', {'open': {'command': "\"python.exe\" \""+args.location+"cloud.py\" \"%1\""}})])
                custom_protocol_register(custom_nx)
            except:
                print "Error! URL Protocol handler installation aborted!"
    #except:
    #    print "Unknown error occurred! Please contact the developers!"
if __name__ == "__main__":
    main()