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

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

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


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",
        type=unicode, 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(
        "-n", "--nx",
        help="Whether we want to install the NX Client or not",
        action="store_true", required=False)
    parser.add_argument(
        "-t", "--target",
        help="If this is an URL icon, where should it point",
        type=unicode, 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():
    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, "CIRCLE Client")
            if os.path.isfile("%s%s" % (location, ".lnk")):
                os.remove("%s%s" % (location, ".lnk"))
                print "%s%s file successfully removed" % (location, ".lnk")
            if os.path.isfile("%s%s" % (location, ".url")):
                os.remove("%s%s" % (location, ".url"))
                print "%s%s file successfully removed" % (location, ".url")
            for subdir, dirs, files in os.walk(args.location):
                for current_file in files:
                    path = os.path.join(subdir, current_file)
                    fileName, fileExtension = os.path.splitext(path)
                    if ((fileExtension == '.pyc' or
                            fileExtension == '.lnk' or
                            fileExtension == '.url' or
                            fileExtension == '.log') and
                            "windowsclasses" not in fileName and
                            "uninstall" not in fileName):
                                os.remove(path)
                                print "%s file successfully removed" % path
        else:
            print "Creating custom URL protocol handler"
            try:
                custom_protocol = OrderedDict([
                    ('circle', ["default",
                                "URL:circle Protocol",
                                "URL Protocol",
                                ""]),
                    ('circle\\URL Protocol', ""),
                    ('circle\\DefaultIcon', args.location + "cloud.ico"),
                    ('circle\\shell', {'open': {
                        'command': (
                            "\"%(prefix)s\pythonw.exe\""
                            " \"%(location)s"
                            "cloud.py\" " % {
                                'prefix': sys.exec_prefix,
                                'location': args.location
                            } + r'"%1"')
                    }})
                ])
                custom_protocol_register(custom_protocol)
            except:
                print "Error! URL Protocol handler installation aborted!"
            print "Creating icon in the installation folder"
            location = os.path.join(desktop_path, "CIRCLE Client.url")
            shortcut = open(location, "w")
            shortcut.write('[InternetShortcut]\n')
            shortcut.write('URL=' + args.target)
            shortcut.close()
            shutil.copy(location, args.location)
            print "Icon successfully created"
    except:
        print "Unknown error occurred! Please contact the developers!"


if __name__ == "__main__":
    main()