#!/usr/pkg/bin/python3.10

# Audio Tools, a module and set of tools for manipulating audio data
# Copyright (C) 2007-2015  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 sys
import os
import os.path
import audiotools
import audiotools.text as _

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

if (__name__ == '__main__'):
    import argparse

    parser = argparse.ArgumentParser(description=_.DESCRIPTION_COVERDUMP)

    parser.add_argument("--version",
                        action="version",
                        version="Python Audio Tools %s" % (audiotools.VERSION))

    parser.add_argument("-V", "--verbose",
                        dest="verbosity",
                        choices=audiotools.VERBOSITY_LEVELS,
                        default=audiotools.DEFAULT_VERBOSITY,
                        help=_.OPT_VERBOSE)

    parser.add_argument("-d", "--dir",
                        dest="dir",
                        default=".",
                        help=_.OPT_DIR_IMAGES)

    parser.add_argument("-p", "--prefix",
                        action="store",
                        dest="prefix",
                        default="",
                        help=_.OPT_PREFIX)

    parser.add_argument("filenames",
                        metavar="FILENAME",
                        nargs="+",
                        help=_.OPT_INPUT_FILENAME)

    options = parser.parse_args()

    msg = audiotools.Messenger(options.verbosity == "quiet")

    audiofiles = audiotools.open_files(options.filenames,
                                       sorted=False,
                                       messenger=msg)
    if len(audiofiles) != 1:
        msg.error(_.ERR_1_FILE_REQUIRED)
        sys.exit(1)
    else:
        audiofile = audiofiles[0]
        input_filename = audiotools.Filename(audiofile.filename)

    metadata = audiofile.get_metadata()
    if metadata is not None:
        # divide images by type (front cover, leaflet page, etc.)
        image_types = {}
        for image in metadata.images():
            image_types.setdefault(image.type, []).append(image)

        # build a set of (Image, Filename) tuples to be extracted
        output_images = []
        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_images.append(
                    (image,
                     audiotools.Filename(
                         os.path.join(
                             options.dir,
                             FILE_TEMPLATE % {
                                 "prefix": options.prefix,
                                 "filename": FILENAME_TYPES[image.type],
                                 "filenum": i + 1,
                                 "suffix": image.suffix()}))))

        # ensure our input file isn't the same
        # as any of the proposed files to extract
        # (this sounds crazy,
        #  but there's no technical reason one's audio file
        #  can't be named "front_cover.jpg"
        #  even if it's not a JPEG
        #  so we have to be sure it's not going to be overwritten)
        if (input_filename in
            [output_filename for
             (image, output_filename) in output_images]):
            msg.error(_.ERR_OUTPUT_IS_INPUT % (input_filename,))
            sys.exit(1)

        # finally, write actual image data to disk if possible
        for (image, output_filename) in output_images:
            try:
                audiotools.make_dirs(str(output_filename))
                f = open(str(output_filename), "wb")
                f.write(image.data)
                f.close()
                msg.info(_.LAB_ENCODE %
                         {"source": input_filename,
                          "destination": output_filename})
            except IOError as e:
                msg.error(_.ERR_ENCODING_ERROR % (output_filename,))
                sys.exit(1)
            except OSError as e:
                msg.os_error(e)
                sys.exit(1)
