#!/usr/bin/python

#Audio Tools, a module and set of tools for manipulating audio data
#Copyright (C) 2007-2012  Brian Langenberger

#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.

#This program is distributed in the hope that it will be useful,
#but WITHOUT ANY WARRANTY; without even the implied warranty of
#MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#GNU General Public License for more details.

#You should have received a copy of the GNU General Public License
#along with this program; if not, write to the Free Software
#Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA


import audiotools
import sys
import os
import os.path
import gettext

gettext.install("audiotools", unicode=True)

FILENAME_TYPES = ("front_cover", "back_cover", "leaflet", "media", "other")

if (__name__ == '__main__'):
    parser = audiotools.OptionParser(
        usage=_(u'%prog [-d directory] <track>'),
        version="Python Audio Tools %s" % (audiotools.VERSION))

    parser.add_option('-V', '--verbose',
                      action='store',
                      dest='verbosity',
                      choices=audiotools.VERBOSITY_LEVELS,
                      default=audiotools.DEFAULT_VERBOSITY,
                      help=_(u'the verbosity level to execute at'))

    parser.add_option('-d', '--dir',
                      action='store',
                      type='string',
                      dest='dir',
                      default='.',
                      help=_(u'the directory to store extracted images'))

    parser.add_option('-p', '--prefix',
                      action='store',
                      dest='prefix',
                      default="",
                      help=_(u'add a prefix to the output image'))

    (options, args) = parser.parse_args()
    msg = audiotools.Messenger("coverdump", options)

    if (len(args) != 1):
        msg.error(_(u"You must specify exactly 1 supported audio file"))
        sys.exit(1)

    try:
        audiofile = audiotools.open(args[0])
    except audiotools.UnsupportedFile:
        msg.error(_(u"%s file format not supported") % msg.filename(args[0]))
        sys.exit(1)
    except IOError:
        msg.error(_(u"Unable to open \"%s\"") % (msg.filename(args[0])))
        sys.exit(1)

    metadata = audiofile.get_metadata()
    if (metadata is not None):
        image_types = {}
        for image in metadata.images():
            image_types.setdefault(image.type, []).append(image)

        for (type, images) in image_types.items():
            if (len(images) != 1):
                FILE_TEMPLATE = \
                    "%(prefix)s%(filename)s%(filenum)2.2d.%(suffix)s"
            else:
                FILE_TEMPLATE = \
                    "%(prefix)s%(filename)s.%(suffix)s"

            for (i, image) in enumerate(images):
                output_filename = os.path.join(
                    options.dir,
                    FILE_TEMPLATE % {"prefix": options.prefix,
                                     "filename": FILENAME_TYPES[image.type],
                                     "filenum": i + 1,
                                     "suffix": image.suffix()})
                try:
                    audiotools.make_dirs(output_filename)
                    f = open(output_filename, "wb")
                    f.write(image.data)
                    f.close()
                    msg.info(
                        _(u"%(source)s -> %(destination)s") %
                        {"source": msg.filename(audiofile.filename),
                         "destination": msg.filename(output_filename)})
                except IOError, e:
                    msg.error(_(u"Unable to write \"%s\"") %
                                  msg.filename(output_filename))
                    sys.exit(1)
                except OSError, e:
                    msg.os_error(e)
                    sys.exit(1)
