#!/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 os.path
import audiotools
import audiotools.text as _

if (__name__ == '__main__'):
    parser = audiotools.OptionParser(
        usage=_.USAGE_TRACKINFO,
        version="Python Audio Tools %s" % (audiotools.VERSION))
    parser.add_option("-n", "--no-metadata",
                      action="store_true", dest="no_metadata",
                      default=False)

    parser.add_option("-L", "--low-level",
                      action="store_true", dest="low_level",
                      default=False)

    parser.add_option("-b", "--bitrate",
                      action="store_true", dest="show_bitrate")

    parser.add_option("-%", "--percentage",
                      action="store_true", dest="show_percentage")

    parser.add_option("-C", "--channel-assignment",
                      action="store_true", dest="channel_assignment")

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

    for file in audiotools.open_files(args, messenger=msg):
        length = int(file.seconds_length())
        if (options.show_bitrate):
            try:
                msg.output(
                    _.LAB_TRACKINFO_BITRATE %
                    {'bitrate': ((os.path.getsize(file.filename) * 8) /
                                 2 ** 10) / length,
                     'filename': audiotools.Filename(file.filename)})
            except ZeroDivisionError:
                msg.output(
                    _.LAB_TRACKINFO_BITRATE %
                    {'bitrate': 0,
                     'filename': audiotools.Filename(file.filename)})
        elif (options.show_percentage):
            try:
                percentage = (float(os.path.getsize(file.filename) * 100) /
                              (file.total_frames() * file.channels() *
                               (file.bits_per_sample() / 8)))
                msg.output(
                    _.LAB_TRACKINFO_PERCENTAGE %
                    {'percentage': int(round(percentage)),
                     'filename': audiotools.Filename(file.filename)})
            except ZeroDivisionError:
                msg.output(_.LAB_TRACKINFO_PERCENTAGE %
                           {'percentage': "0",
                            'filenam': audiotools.Filename(file.filename)})
        else:
            msg.output(
                _.LAB_TRACKINFO_ATTRIBS %
                {"minutes": length / 60,
                 "seconds": length % 60,
                 "channels": file.channels(),
                 "rate": audiotools.khz(file.sample_rate()),
                 "bits": file.bits_per_sample(),
                 "filename": audiotools.Filename(file.filename)})
        if (not options.no_metadata):
            metadata = file.get_metadata()
            if (not options.low_level):
                if (metadata is not None):
                    msg.output(unicode(metadata))
                    msg.output(u"")
                replay_gain = file.replay_gain()
                if (replay_gain is not None):
                    msg.output(_.LAB_TRACKINFO_REPLAYGAIN)
                    msg.new_row()
                    msg.output_column(_.LAB_TRACKINFO_TRACK_GAIN, True)
                    msg.output_column(unicode(replay_gain.track_gain) + u" dB")
                    msg.new_row()
                    msg.output_column(_.LAB_TRACKINFO_TRACK_PEAK, True)
                    msg.output_column(u"%f" % (replay_gain.track_peak))
                    msg.new_row()
                    msg.output_column(_.LAB_TRACKINFO_ALBUM_GAIN, True)
                    msg.output_column(unicode(replay_gain.album_gain) + u" dB")
                    msg.new_row()
                    msg.output_column(_.LAB_TRACKINFO_ALBUM_PEAK, True)
                    msg.output_column(u"%f" % (replay_gain.album_peak))
                    msg.output_rows()
                    msg.output(u"")
                cuesheet = file.get_cuesheet()
                if (cuesheet is not None):
                    ISRCs = cuesheet.ISRCs()
                    msg.output(_.LAB_TRACKINFO_CUESHEET)
                    msg.new_row()
                    msg.output_column(u"  ")
                    msg.output_column(_.LAB_TRACKINFO_CUESHEET_TRACK, True)
                    msg.output_column(u"  ")
                    msg.output_column(_.LAB_TRACKINFO_CUESHEET_LENGTH, True)
                    msg.output_column(u"  ")
                    msg.output_column(_.LAB_TRACKINFO_CUESHEET_ISRC)
                    for (i, pcm_length) in enumerate(
                        cuesheet.pcm_lengths(file.total_frames(),
                                             file.sample_rate())):
                        ISRC = ISRCs.get(i + 1, None)
                        msg.new_row()
                        msg.output_column(u"")
                        msg.output_column(unicode(i + 1), True)
                        msg.output_column(u"")
                        msg.output_column(
                            _.LAB_TRACK_LENGTH % (pcm_length /
                                                  file.sample_rate() / 60,
                                                  pcm_length /
                                                  file.sample_rate() % 60),
                            True)
                        msg.output_column(u"")
                        if (ISRC is not None):
                            msg.output_column(ISRC.decode('ascii'))
                        else:
                            msg.output_column(u"")
                    msg.output_rows()
                    msg.output(u"")
            else:
                if (metadata is not None):
                    msg.output(metadata.raw_info())
                    msg.output(u"")
        if (options.channel_assignment):
            msg.output(_.LAB_TRACKINFO_CHANNELS)

            channel_names = dict(
                [(attr, audiotools.ChannelMask.MASK_TO_NAME[mask])
                 for (attr, mask) in
                 audiotools.ChannelMask.SPEAKER_TO_MASK.items()])

            if (file.channel_mask().defined()):
                for (i, channel) in enumerate(file.channel_mask().channels()):
                    msg.output(_.LAB_TRACKINFO_CHANNEL %
                               {"channel_number": i + 1,
                                "channel_name": channel_names[channel]})
            else:
                for i in xrange(file.channels()):
                    msg.output(_.LAB_TRACKINFO_CHANNEL %
                               {"channel_number": i + 1,
                                "channel_name": _.LAB_TRACKINFO_UNDEFINED})
