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

"""
Windows icon installer for CIRCLE client application
"""

import os
import argparse
import subprocess
import pythoncom
import shutil
from win32com.shell import shell, shellcon
import windowsclasses
try:
    from collections import *
except ImportError:
    from OrderedDict import *



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

    Keyword arguments:
    @return args -- arguments given by console
    """
    parser = argparse.ArgumentParser()
    parser.add_argument(
        "-d", "--driver",
        help="Select webdriver. Aside from Firefox, you have to install "+
        "first the proper driver.", type=str, default="firefox",
        required=False, choices=['firefox', 'chrome',
                                'iexplore', 'opera'])
    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, 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://cloud.bme.hu/", required=False)
    args = parser.parse_args()
    return args
    
def custom_protocol_register(custom_protocol):
    """
    Custom protocol register based on RegistryHandler module
    Can raise AttributeError on wrongly provided dictionary chain

    Keyword arguments:
    @param dict_chain -- OrderedDictionary chain of the registry tree
    """
    if not isinstance(custom_protocol, OrderedDict):
        raise AttributeError
    print "\t"+custom_protocol.iterkeys().next()
    try:
        custom_arguments = windowsclasses.Struct()
        custom_arguments.registry = "HKCR"
        handler = windowsclasses.RegistryHandler(custom_arguments)
        handler.create_registry_from_dict_chain(custom_protocol, True)
        print "\t\tDone!"
    except:
        raise
    

def main():
    """
    Main program

    Jobs:
    read the parameters
    create a proper icon with the proper driver (or delete)
    call the nx_client_installer
    """
    try:
        args = parse_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 %s\\nx_client_installer.py" % os.path.dirname(
                    os.path.realpath(__file__)))
            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)
                location = os.path.join(desktop_path, "Cloud GUI.lnk")
                persist_file.Save(location, 0)
            print "Icon successfully created on desktop"
            shutil.copy(location, args.location)
            print "Creating custom URL protocol handlers"
            try:
                custom_ssh = OrderedDict(
                    [('ssh', ["default", "URL:ssh Protocol", "URL Protocol", ""]),
                    ('ssh\\URL Protocol', ""),
                    ('ssh\\DefaultIcon', args.location+"cloud.ico"),
                    ('ssh\\shell', {'open': {
                        'command': "\"python.exe\" \"%s" % args.location+
                        "cloud.py\" \"%1\""}})])
                custom_protocol_register(custom_ssh)
                custom_rdp = OrderedDict(
                    [('rdp', ["default", "URL:rdp Protocol", "URL Protocol", ""]),
                    ('rdp\\URL Protocol', ""),
                    ('rdp\\DefaultIcon', args.location+"cloud.ico"),
                    ('rdp\\shell', {'open': {
                        'command': "\"python.exe\" \"%s" % args.location+
                        "cloud.py\" \"%1\""}})])
                custom_protocol_register(custom_rdp)
                custom_nx = OrderedDict(
                    [('nx', ["default", "URL:nx Protocol", "URL Protocol", ""]),
                    ('nx\\URL Protocol', ""),
                    ('nx\\DefaultIcon', args.location+"cloud.ico"),
                    ('nx\\shell', {'open': {
                        'command': "\"python.exe\" \"%s" % 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()