#!/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 audiotools.cue
import audiotools.ui
import sys
import os
import os.path
import gettext

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


def has_embedded_cuesheet(audiofile):
    return audiofile.get_cuesheet() is not None

if (__name__ == '__main__'):
    parser = audiotools.OptionParser(
        _(u'%prog [options] [-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(
        '--cue',
        action='store',
        type='string',
        dest='cuesheet',
        metavar='FILENAME',
        help=_(u'the cuesheet to use for splitting track'))

    conversion = audiotools.OptionGroup(parser, _(u"Encoding Options"))

    conversion.add_option(
        '-t', '--type',
        action='store',
        dest='type',
        choices=audiotools.TYPE_MAP.keys(),
        help=_(u'the type of audio track to convert to'))

    conversion.add_option(
        '-q', '--quality',
        action='store',
        type='string',
        dest='quality',
        help=_(u'the quality to store audio tracks at'))

    conversion.add_option(
        '-d', '--dir',
        action='store',
        type='string',
        dest='dir',
        default='.',
        help=_(u'the directory to store converted audio tracks'))

    conversion.add_option(
        '--format',
        action='store',
        type='string',
        default=None,
        dest='format',
        help=_(u'the format string for new filenames'))

    parser.add_option_group(conversion)

    lookup = audiotools.OptionGroup(parser, _(u"CD Lookup Options"))

    lookup.add_option(
        '--musicbrainz-server', action='store',
        type='string', dest='musicbrainz_server',
        default=audiotools.MUSICBRAINZ_SERVER,
        metavar='HOSTNAME')
    lookup.add_option(
        '--musicbrainz-port', action='store',
        type='int', dest='musicbrainz_port',
        default=audiotools.MUSICBRAINZ_PORT,
        metavar='PORT')
    lookup.add_option(
        '--no-musicbrainz', action='store_false',
        dest='use_musicbrainz',
        default=audiotools.MUSICBRAINZ_SERVICE,
        help='do not query MusicBrainz for metadata')

    lookup.add_option(
        '--freedb-server', action='store',
        type='string', dest='freedb_server',
        default=audiotools.FREEDB_SERVER,
        metavar='HOSTNAME')
    lookup.add_option(
        '--freedb-port', action='store',
        type='int', dest='freedb_port',
        default=audiotools.FREEDB_PORT,
        metavar='PORT')
    lookup.add_option(
        '--no-freedb', action='store_false',
        dest='use_freedb',
        default=audiotools.FREEDB_SERVICE,
        help='do not query FreeDB for metadata')

    lookup.add_option(
        '-I', '--interactive',
        action='store_true',
        default=False,
        dest='interactive',
        help=_(u'edit metadata in interactive mode'))

    lookup.add_option(
        '-D', '--default',
        dest='use_default', action='store_true', default=False,
        help=_(u'when multiple choices are available, ' +
               u'select the first one automatically'))

    parser.add_option_group(lookup)

    metadata = audiotools.OptionGroup(parser, _(u"Metadata Options"))

    metadata.add_option(
        '--album-number',
        dest='album_number',
        action='store',
        type='int',
        default=0,
        help=_(u'the album number of this CD, ' +
               u'if it is one of a series of albums'))

    metadata.add_option(
        '--album-total',
        dest='album_total',
        action='store',
        type='int',
        default=0,
        help=_(u'the total albums of this CD\'s set, ' +
               u'if it is one of a series of albums'))

    #if adding ReplayGain is a lossless process
    #(i.e. added as tags rather than modifying track data)
    #add_replay_gain should default to True
    #if not, add_replay_gain should default to False
    #which is which depends on the track type
    metadata.add_option(
        '--replay-gain',
        action='store_true',
        dest='add_replay_gain',
        help=_(u'add ReplayGain metadata to newly created tracks'))

    metadata.add_option(
        '--no-replay-gain',
        action='store_false',
        dest='add_replay_gain',
        help=_(u'do not add ReplayGain metadata to newly extracted tracks'))

    parser.add_option_group(metadata)

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

    #ensure interactive mode is available, if selected
    if (options.interactive and (not audiotools.ui.AVAILABLE)):
        audiotools.ui.not_available_message(msg)
        sys.exit(1)

    #get the AudioFile class we are converted to
    if (options.type is not None):
        AudioType = audiotools.TYPE_MAP[options.type]
    else:
        AudioType = audiotools.TYPE_MAP[audiotools.DEFAULT_TYPE]

    #ensure the selected compression is compatible with that class
    if (options.quality == 'help'):
        if (len(AudioType.COMPRESSION_MODES) > 1):
            msg.info(_(u"Available compression types for %s:") % \
                         (AudioType.NAME))
            for mode in AudioType.COMPRESSION_MODES:
                msg.new_row()
                if (mode == audiotools.__default_quality__(AudioType.NAME)):
                    msg.output_column(msg.ansi(mode.decode('ascii'),
                                               [msg.BOLD,
                                                msg.UNDERLINE]), True)
                else:
                    msg.output_column(mode.decode('ascii'), True)
                if (mode in AudioType.COMPRESSION_DESCRIPTIONS):
                    msg.output_column(u" : ")
                else:
                    msg.output_column(u"   ")
                msg.output_column(
                    AudioType.COMPRESSION_DESCRIPTIONS.get(mode, u""))
            msg.info_rows()
        else:
            msg.error(_(u"Audio type %s has no compression modes") % \
                            (AudioType.NAME))
        sys.exit(0)
    elif (options.quality is None):
        options.quality = audiotools.__default_quality__(AudioType.NAME)
    elif (options.quality not in AudioType.COMPRESSION_MODES):
        msg.error(_(u"\"%(quality)s\" is not a supported " +
                    u"compression mode for type \"%(type)s\"") %
                  {"quality": options.quality,
                   "type": AudioType.NAME})
        sys.exit(1)

    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"You must specify exactly 1 supported audio file"))
        sys.exit(1)
    except IOError:
        msg.error(_(u"Unable to open \"%s\"") % (msg.filename(args[0])))
        sys.exit(1)

    if (options.add_replay_gain is None):
        options.add_replay_gain = (
            audiotools.ADD_REPLAYGAIN and
            AudioType.lossless_replay_gain() and
            audiotools.applicable_replay_gain([audiofile]))

    if ((options.cuesheet is None) and (not has_embedded_cuesheet(audiofile))):
        msg.error(_(u"You must specify a cuesheet to split audio file"))
        sys.exit(1)

    base_directory = options.dir
    encoded_filenames = []

    if (options.cuesheet is not None):
        #grab the cuesheet we're using to split tracks
        #(this overrides an embedded cuesheet)
        try:
            cuesheet = audiotools.read_sheet(options.cuesheet)
        except audiotools.SheetException, err:
            msg.error(unicode(err))
            sys.exit(1)
    else:
        cuesheet = audiofile.get_cuesheet()

    if (list(cuesheet.pcm_lengths(audiofile.total_frames()))[-1] <= 0):
        msg.error(_(u"Cuesheet too long for track being split"))
        sys.exit(1)

    #use cuesheet to query metadata services for metadata choices
    metadata_choices = audiotools.metadata_lookup(
        first_track_number=1,
        last_track_number=len(list(cuesheet.indexes())),
        offsets=[i[-1] + 150 for i in cuesheet.indexes()],
        lead_out_offset=audiofile.cd_frames() + 150,
        total_length=audiofile.cd_frames(),
        musicbrainz_server=options.musicbrainz_server,
        musicbrainz_port=options.musicbrainz_port,
        freedb_server=options.freedb_server,
        freedb_port=options.freedb_port,
        use_musicbrainz=options.use_musicbrainz,
        use_freedb=options.use_freedb)

    #populate any empty Album-level metadata fields
    #with those from original file
    album_metadata = audiofile.get_metadata()
    if (album_metadata is not None):
        album_fields = dict([(attr, field) for (attr, field) in
                             album_metadata.filled_fields()
                             if (attr in set(["album_name",
                                              "artist_name",
                                              "performer_name",
                                              "composer_name",
                                              "conductor_name",
                                              "media",
                                              "catalog",
                                              "copyright",
                                              "publisher",
                                              "year",
                                              "date",
                                              "album_number",
                                              "album_total",
                                              "comment"]))])

        for c in metadata_choices:
            for m in c:
                for (attr, field) in m.empty_fields():
                    if (attr in album_fields):
                        setattr(m, attr, album_fields[attr])

    #update MetaData with command-line album-number/total, if given
    if (options.album_number != 0):
        for c in metadata_choices:
            for m in c:
                m.album_number = options.album_number

    if (options.album_total != 0):
        for c in metadata_choices:
            for m in c:
                m.album_total = options.album_total

    #decide which metadata to use to tag split tracks
    if (options.interactive):
        #pick choice using interactive widget
        metadata_widget = audiotools.ui.MetaDataFiller(metadata_choices)
        loop = audiotools.ui.urwid.MainLoop(
            metadata_widget,
            [('key', 'white', 'dark blue')],
            unhandled_input=metadata_widget.handle_text)
        loop.run()

        track_metadatas = dict([(m.track_number, m) for m in
                                metadata_widget.populated_metadata()])
    else:
        if ((len(metadata_choices) == 1) or options.use_default):
            #use default choice
            track_metadatas = dict([(m.track_number, m) for m in
                                    metadata_choices[0]])
        else:
            #pick choice using raw stdin/stdout
            track_metadatas = \
                dict([(m.track_number, m) for m in
                      audiotools.ui.select_metadata(metadata_choices, msg)])

    #pull ISRC metadata from the cuesheet, if any
    cuesheet_ISRCs = cuesheet.ISRCs()
    for metadata in track_metadatas.values():
        if ((len(metadata.ISRC) == 0) and
            (metadata.track_number in cuesheet_ISRCs.keys())):
            metadata.ISRC = \
                cuesheet_ISRCs[metadata.track_number].decode('ascii',
                                                             'replace')

    #perform actual track splitting and tagging
    encoded_files = []
    total_pcm = audiotools.BufferedPCMReader(audiofile.to_pcm())

    try:
        for (i, pcm_frames) in enumerate(
            cuesheet.pcm_lengths(audiofile.total_frames())):
            track_number = i + 1
            track_metadata = track_metadatas.get(track_number, None)

            filename = os.path.join(
                base_directory,
                AudioType.track_name(
                    file_path=audiofile.filename,
                    track_metadata=track_metadata,
                    format=options.format))

            audiotools.make_dirs(filename)

            progress = audiotools.SingleProgressDisplay(
                msg, msg.filename(filename))

            #FIXME - catch from_pcm errors here
            encoded_files.append(
                AudioType.from_pcm(
                    filename,
                    audiotools.PCMReaderProgress(
                        audiotools.LimitedPCMReader(total_pcm, pcm_frames),
                        pcm_frames,
                        progress.update),
                    options.quality))
            encoded_files[-1].set_metadata(track_metadata)
            progress.clear()
            msg.info(u"%s -> %s" %
                     (msg.filename(audiofile.filename),
                      msg.filename(filename)))

    except audiotools.UnsupportedTracknameField, err:
        err.error_msg(msg)
        sys.exit(1)
    except audiotools.EncodingError, err:
        msg.error(unicode(err))
        sys.exit(1)

    #apply ReplayGain to split tracks, if requested
    if (options.add_replay_gain and AudioType.can_add_replay_gain()):
        rg_progress = audiotools.ReplayGainProgressDisplay(
                msg, AudioType.lossless_replay_gain())
        rg_progress.initial_message()
        try:
            #separate encoded files by album_name and album_number
            for album in audiotools.group_tracks(encoded_files):
                #add ReplayGain to groups of files
                #belonging to the same album

                AudioType.add_replay_gain([a.filename for a in album],
                                          rg_progress.update)
        except ValueError, err:
            rg_progress.clear()
            msg.error(unicode(err))
            sys.exit(1)
        rg_progress.final_message()
