#@+leo-ver=5-thin
#@+node:maphew.20130611235500.2665: * @file unregister-leo.leox
#@@language python
#@@tabwidth -4
'''Remove registry key for Leo file type and .leo file association'''
#@+others
#@+node:mhw-debug-1081.20190216130451.1: ** imports
#py2 shims
from __future__ import unicode_literals
from __future__ import print_function
from __future__ import division
from __future__ import absolute_import
from future import standard_library
standard_library.install_aliases()

import leo
import leo.core.leoGlobals as g
import os
import sys
import shutil
import subprocess
from winreg import *

#@+node:mhw-debug-1081.20190216145532.1: ** unregister_leo
def unregister_leo():
    try:
        leoKey = OpenKey(HKEY_CLASSES_ROOT, "Leo.File")
        DeleteKey(leoKey, "Shell\\Open\\Command")
        DeleteKey(leoKey, "Shell\\Open")
        DeleteKey(leoKey, "Shell")
        DeleteKey(leoKey, "DefaultIcon")
        DeleteKey(HKEY_CLASSES_ROOT, "Leo.File")        
        # CloseKey(leoKey)
        g.es_print("  Leo file type has been removed from registry")
    except WindowsError as e:
        g.es_print("  Unregistering Leo file type failed: ", e)  

    try:
        DeleteKey(HKEY_CLASSES_ROOT, ".leo")
        DeleteKey(HKEY_CLASSES_ROOT, ".leox")
        g.es_print("  .leo, .leox file associations removed from registry")
    except WindowsError as e:
        g.es_print("  Removing .leo, leox associations failed: ", e)
#@+node:mhw-debug-1081.20190314005003.1: ** relaunch_elevated
def relaunch_elevated(script):
    g.es_print('--- Relaunching and asking for elevated permissions')
    g.execute_shell_commands(['&{} {} {}'.format(
        sys.executable,
        elevate,
        script)])
    g.es_print('---')
    
#@+node:mhw-debug-1081.20190314004045.1: ** get_my_path
def get_my_path():
    '''Return full path of currently running script or executable
    
   Thanks to
        https://stackoverflow.com/questions/2632199/
            how-do-i-get-the-path-of-the-current-executed-file-in-python
        @jose-crespo-barrios, https://stackoverflow.com/a/44592299/14420
    '''
    import inspect
    filename = inspect.getframeinfo(inspect.currentframe()).filename
    return filename
#@-others

# define script names and paths
scripts_path = os.path.realpath(os.path.join(leo.__path__[0], 'scripts/win'))
elevate = os.path.join(scripts_path, 'elevate.py')
this_script = get_my_path()

import ctypes, sys
if not ctypes.windll.shell32.IsUserAnAdmin():
    g.es_print("No admin privileges")
    relaunch_elevated(this_script)
else:
    g.es_print("--- Running unregister-leo Leo script")
    g.es_print("  Attempting to un-register leo filetype with Windows...")
    unregister_leo()
    g.es_print('--- end of script')
#@-leo
