#!/usr/bin/python
# -*- coding: iso-8859-1 -*-
#
# Album Cover Art Downloader
# Copyright (C) 2003, 2004 Sami Kystil <skyostil@kempele.fi>
# 
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# at your option) any later version.

import os
import sys
import getopt

# Register the latin-1 encoding
import codecs
import encodings.iso8859_1
import encodings.utf_8
codecs.register(lambda encoding: encodings.iso8859_1.getregentry())
codecs.register(lambda encoding: encodings.utf_8.getregentry())
assert codecs.lookup("iso-8859-1")
assert codecs.lookup("utf-8")

#
# @returns the directory where the script resides
#
def getBaseDir():
  path = os.path.dirname(sys.argv[0])
  if os.path.split(path)[-1] == 'bin':
    path = os.path.dirname(path)
  return path

#
# @returns the directory for library files
#
def getLibDir():
  return os.path.join(getBaseDir(), "/", "usr", "lib", "python2.7", "site-packages" , "albumart")

#
# @returns the directory for shared data files
#
def getShareDir():
    return os.path.join(getBaseDir(), "/", "usr", "share", "albumart")

# find out where our program and data files are and set up sys.path accordingly.
sys.path = [getBaseDir(), getLibDir()] + sys.path

import version

#
# Prints program usage information to stdout.
#
def printUsage():
  print """\
%(app)s version %(version)s by %(author)s
http://kempele.fi/~skyostil/projects/albumart

Assigns cover images to directories holding albums.

Usage:
  %(executable)-18s    [options] [path]
Options:
  -h, --help           This text.
  -d, --download       Download covers for the given path.
  -x, --delete         Remove covers below the given path.
  -s, --synchronize    Synchronizes all covers below the given path.
  -H, --hidden         Don't show a progress dialog.
  -i, --summary        Show a dialog with summary information when done.""" % \
  {
    "executable" : sys.argv[0],
    "app" : version.__program__, 
    "version" : version.__version__, 
    "author" : version.__author__
  }

#
# Run the graphical user interface
#
# @param albumPath Initial album path.
#                  Pass None to have it read from the config file.
# @returns a numeric exit code (0 for success)
#
def runGui(albumPath = None):
  # load the heavy modules on demand
  import albumart_dialog
  import qt

  app = qt.QApplication(sys.argv)
  mainwin = albumart_dialog.AlbumArtDialog(dataPath = getShareDir(), albumPath = albumPath)
  app.setMainWidget(mainwin)
  mainwin.show()
  return app.exec_loop()

#
# Run the unattended graphical user interface
#
# @returns a numeric exit code (0 for success)
#
def runUnattendedGui(operation, albumPath, showSummary = False, hidden = False):
  # load the heavy modules on demand
  import albumart_unattended_ui
  import qt
  
  app = qt.QApplication(sys.argv)
  ui = albumart_unattended_ui.AlbumArtUnattendedUi(showSummary = showSummary,
                                                   hidden = hidden)
  app.setMainWidget(ui)
  
  if operation == "download":
    ui.downloadCovers(albumPath)
  elif operation == "delete":
    ui.deleteCovers(albumPath)
  elif operation == "synchronize":
    ui.synchronizeCovers(albumPath)
    
  return app.exec_loop()

if __name__=="__main__":
  # fix output streams on windows
  if os.name == "nt" and sys.argv[0].lower().endswith(".exe"):
    sys.stdout = sys.stderr = \
      open(os.path.join(os.path.dirname(sys.argv[0]), "log.txt"), "w")

  try:
    opts, args = getopt.getopt(sys.argv[1:],
                               "hdxsiH",
                               ["help", "download", "delete", "synchronize",
                                "summary", "hidden"])
  except getopt.GetoptError:
    printUsage()
    sys.exit(2)
  
  operation = None
  showSummary = False
  hidden = False
  
  for option, arg in opts:
    if option in ("-h", "--help"):
      printUsage()
      sys.exit()
    elif option in ("-d", "--download"):
      operation = "download"
    elif option in ("-x", "--delete"):
      operation = "delete"
    elif option in ("-s", "--synchronize"):
      operation = "synchronize"
    elif option in ("-i", "--summary"):
      showSummary = True
    elif option in ("-H", "--hidden"):
      hidden = True
      
  if not args:
    sys.exit(runGui())
  else:
    if operation:
      sys.exit(runUnattendedGui(operation, args[0], showSummary, hidden))
    else:
      sys.exit(runGui(args[0]))
