# Wizard Kit: Find user wallpaper(s)

import os
import sys

# STATIC VARIABLES
EXPLORER_LOCATIONS = [
  r'{APPDATA}\Microsoft\Internet Explorer\Internet Explorer Wallpaper.bmp',
  r'{APPDATA}\Microsoft\Windows\Themes\TranscodedWallpaper.jpg',
  r'{APPDATA}\Mozilla\Firefox\Desktop Background.bmp',
  ]
REG_HKCU_LOCATIONS = {
  r'Control Panel\Desktop': 'Wallpaper',
  r'Software\Microsoft\Internet Explorer\Desktop\General': 'WallpaperSource',
  }

# Init
os.chdir(os.path.dirname(os.path.realpath(__file__)))
sys.path.append(os.getcwd())
from functions.cleanup import *
init_global_vars()
os.system('title {}: Find user wallpaper(s)'.format(KIT_NAME_FULL))

if __name__ == '__main__':
  try:
    stay_awake()
    clear_screen()

    # Build list of wallpaper paths
    wall_paths = [s.format(**global_vars['Env']) for s in EXPLORER_LOCATIONS]
    for k, v in REG_HKCU_LOCATIONS.items():
      with winreg.OpenKey(HKCU, k) as key:
        try:
          _path = winreg.QueryValueEx(key, v)[0]
        except Exception:
          # Meh, ignore
          pass
        else:
          wall_paths.append(_path)

    # Copy files into ClientDir
    dest_folder = r'{}\{}\Wallpapers'.format(
      global_vars['BackupDir'],
      global_vars['Env']['USERNAME'],
      )
    os.makedirs(dest_folder, exist_ok=True)
    for source_path in wall_paths:
      if os.path.exists(source_path):
        dest_path = '{}\{}'.format(
          dest_folder,
          re.sub(r'^.*\\', '', source_path),
          )
        dest_path = non_clobber_rename(dest_path)
        try:
          shutil.copy(source_path, dest_path)
        except Exception:
          # Meh, ignore
          pass

    # Open folder if wallpapers were copied or report error
    delete_empty_folders(dest_folder.replace(r'\Wallpaper', ''))
    if os.path.exists(dest_folder):
      popen_program(['explorer', dest_folder])
    else:
      print_warning('No wallpapers found.')
      pause('Press Enter to exit...')

    # TODO: DELETEME
    print('Wall paths:')
    for p in wall_paths:
      print('  ', p)
    pause('Meh?')

    # Done
    exit_script()
  except SystemExit as sys_exit:
    exit_script(sys_exit.code)
  except:
    major_exception()

# vim: sts=2 sw=2 ts=2
