#!/usr/bin/env python2
import os, sys, getopt;
import eyeD3, eyeD3.utils;
from getopt import getopt, GetoptError;

#######################################################################
class ProgOpts:
   progName = "";
   files = [];
   showFrames = 0;
   writeImages = 0;

#######################################################################
# Return a string contain program usage information.
def usage(progName):
   return \
"""
%s version %s written by %s

%s [OPTS] file [file...]
ARGS:
        file [file...]   The mp3 files to read.

OPTS:
        --frames       Output all raw ID3 frames.
        --genres       Display the table of ID3 genres and exit.
        --write-images Causes all attqacahed images (APIC frames) to be 
                       written to the current directory.
        --verbose      Display detailed tag information during parsing.
        -v,--version   Display program version and exit.
        -h,--help      Display program help info and exit.
""" % (progName, eyeD3.version, eyeD3.maintainer, progName);

#######################################################################
def printGenres():
   for i in range(len(eyeD3.genres)):
      name = eyeD3.genres[i];
      if name:
         print "%3d: %s" % (i, name);

#######################################################################
def parseCommandLine(progOpts):
   progOpts.progName = os.path.basename(sys.argv[0]);

   try:
      opts, args = getopt(sys.argv[1:], "hv",
                          ["help", "version", "frames", "genres",
                           "verbose", "write-images"]);
   except GetoptError, ex:
      print ex;
      print usage(progOpts.progName);
      sys.exit(1);

   for o, a in opts:
      if o in ("-h", "--help"):
         print usage(progOpts.progName);
         sys.exit(0);
      elif o in ("-v", "--version"):
         print progOpts.progName, "version", eyeD3.version;
         sys.exit(0);
      elif o == "--frames":
         progOpts.showFrames = 1;
      elif o == "--genres":
         printGenres();
         sys.exit(0);
      elif o == "--verbose":
         eyeD3.utils.TRACE = 1;
      elif o == "--write-images":
         progOpts.writeImages = 1;

   if len(args) == 0:
      print "Missing file argument";
      print usage(progOpts.progName);
      sys.exit(1);

   progOpts.files = args;

#######################################################################
def showAudioInfo(audioInfo):
   if isinstance(audioInfo, eyeD3.Mp3AudioFile):
      print ""
      print "++++++++++++++++++++++++++++++++++++++++++++++++++++++++++";
      print "File: %s" % audioInfo.fileName;
      print "Size: %.2f MB" % (float(audioInfo.getSize()) / 1048576.0);
      print "MPEG%d, Layer %s" % (audioInfo.header.version,
                                  "I" * audioInfo.header.layer);
      print "Bit Rate: %s" % audioInfo.getBitRateString();
      print "Frequency: %s Hz" % audioInfo.header.sampleFreq;
      print "Copyright: %s" % audioInfo.header.copyright;
      print "Original: %s" % audioInfo.header.original;
      print "Mode: %s" % audioInfo.header.mode;
      print "Time: %s " % audioInfo.getPlayTimeString();
      print "";
   else:
      raise TypeError();

#######################################################################
def main():
   opts = ProgOpts();
   parseCommandLine(opts);

   for f in opts.files:
      try:
         if eyeD3.isMp3File(f):
            mp3File = eyeD3.Mp3AudioFile(f);
            showAudioInfo(mp3File);
            id3Tag = mp3File.getTag();
         else:
            id3Tag = eyeD3.Tag();
            if not id3Tag.link(f):
               id3Tag = None;
      except eyeD3.InvalidAudioFormatException, ex:
         print "Error with", f;
         print str(ex);
         continue;
      except IOError, ex:
         print ex;
         continue;
      except eyeD3.TagException, ex:
         print ex;
         continue;

      # Display ID3 tag contents.
      if id3Tag == None:
         print "No ID3 Tag found!";
         continue;

      print "ID3 v%s tag info:" % id3Tag.getVersion();
      print "Artist:", id3Tag.getArtist();
      print "Album:", id3Tag.getAlbum();
      print "Title:", id3Tag.getTitle();
      print "Year:", id3Tag.getYear();
      (trackNum, trackTotal) = id3Tag.getTrackNum();
      print "Track Number:", trackNum;
      print "Track Total:", trackTotal;

      try:
         genre = id3Tag.getGenre();
         if genre:
            print "Genre: %s (id %d)" % (genre.getName(), genre.getId());
      except eyeD3.GenreException, ex:
         print ex;

      comments = id3Tag.getComments();
      if comments:
         print "\nTag Comments:";
      for c in comments:
         cDesc = c.description;
         if not cDesc:
            cDesc = "Comment";
         cText = c.comment;
         print "%s: %s" % (cDesc, cText);

      userTextFrames = id3Tag.getUserTextFrames();
      if userTextFrames:
         print "\nTag User Text:";
      for f in userTextFrames:
         desc = f.description;
         if not desc:
            desc = "User Text Frame (TXXX)";
         text = f.text;
         print "%s:\n%s" % (desc, text);

      urls = id3Tag.getURLs();
      if urls:
         print "\nTag URLs:";
      for u in urls:
         if u.header.id != eyeD3.frames.USERURL_FID:
            print "%s: %s" % (u.header.id, u.url);
         else:
            print "%s - %s:\n%s" % (u.header.id, u.description, u.url);

      images = id3Tag.getImages();
      if images:
         print "\nTag Images:";
      for img in images:
         print "%s Image: %d byte %s" %\
               (img.picTypeToString(img.pictureType),
                len(img.imageData), img.mimeType);
         print "Description: %s" % img.description;
         print "\n";
         if opts.writeImages:
            print "Writing %s..." % img.getDefaultFileName();
            img.writeFile();

      if opts.showFrames:
         print "-------------------------------------------------------";
         print "ID3 Frames:";
         for frm in id3Tag:
            print frm;

#######################################################################
if __name__ == "__main__":
    main();
