#!/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 gettext

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

if (__name__ == '__main__'):
    parser = audiotools.OptionParser(
        usage=_(u"%prog [options] <track 1> [track 2] ..."),
        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(
                    _(u"%(bitrate)4.4s kbps: %(filename)s") %
                    {'bitrate': ((os.path.getsize(file.filename) * 8) /
                                 2 ** 10) / length,
                     'filename': msg.filename(file.filename)})
            except ZeroDivisionError:
                msg.output(
                    _(u"%(bitrate)4.4s kbps: %(filename)s") %
                    {'bitrate': 0,
                     'filename': msg.filename(file.filename)})
        elif (options.show_percentage):
            try:
                msg.output(
                    _(u"%(percentage)3.3s%%: %(filename)s") %
                    {'percentage':
                         int(round(float(
                           os.path.getsize(file.filename) * 100) /
                                   (file.total_frames() * file.channels() *
                                    (file.bits_per_sample() / 8)))),
                     'filename': msg.filename(file.filename)})
            except ZeroDivisionError:
                msg.output(_(u"%(percentage)3.3s%%: %(filename)s") % \
                               {'percentage': "0",
                                'filenam': msg.filename(file.filename)})
        else:
            msg.output(
                _(u"%(minutes)2.2d:%(seconds)2.2d " +
                  u"%(channels)dch %(rate)dHz %(bits)d-bit: %(filename)s") %
                {"minutes": length / 60,
                 "seconds": length % 60,
                 "channels": file.channels(),
                 "rate": file.sample_rate(),
                 "bits": file.bits_per_sample(),
                 "filename": msg.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(_(u"ReplayGain:"))
                    msg.new_row()
                    msg.output_column(_(u"Track Gain : "), True)
                    msg.output_column(unicode(replay_gain.track_gain) + u" dB")
                    msg.new_row()
                    msg.output_column(_(u"Track Peak : "), True)
                    msg.output_column(u"%f" % (replay_gain.track_peak))
                    msg.new_row()
                    msg.output_column(_(u"Album Gain : "), True)
                    msg.output_column(unicode(replay_gain.album_gain) + u" dB")
                    msg.new_row()
                    msg.output_column(_(u"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(_(u"Cuesheet:"))
                    msg.new_row()
                    msg.output_column(u"  ")
                    msg.output_column(_(u"track"), True)
                    msg.output_column(u"  ")
                    msg.output_column(_(u"length"), True)
                    msg.output_column(u"  ")
                    msg.output_column(_(u"ISRC"))
                    for (i, pcm_length) in enumerate(
                        cuesheet.pcm_lengths(file.total_frames())):
                        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(
                            u"%d:%2.2d" % (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(_("Assigned Channels:"))
            channel_names = {
                "front_left": _(u"Front Left"),
                "front_right": _(u"Front Right"),
                "front_center": _(u"Front Center"),
                "low_frequency": _(u"Low Frequency"),
                "back_left": _(u"Back Left"),
                "back_right": _(u"Back Right"),
                "front_left_of_center": _(u"Front Left of Center"),
                "front_right_of_center": _(u"Front Right of Center"),
                "back_center": _(u"Back Center"),
                "side_left": _(u"Side Left"),
                "side_right": _(u"Side Right"),
                "top_center": _(u"Top Center"),
                "top_front_left": _(u"Top Front Left"),
                "top_front_center": _(u"Top Front Center"),
                "top_front_right": _(u"Top Front Right"),
                "top_back_left": _(u"Top Back Left"),
                "top_back_center": _(u"Top Back Center"),
                "top_back_right": _(u"Top Back Right")}

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