#!/usr/bin/env python

__AUTHOR__ = "Kun Xi"
__VERSION__ = "0.1.1"
__LICENSE__ = "GPL"

import getopt, sys, re, os
from eyeD3 import *

def usage():
	print """Usage: eyeD3conv [OPTION...] [MP3_FILE...]
Convert encoding of given mp3 files' ID3 tags from one encoding to another.

Input/Output format specification:
  -f, --from-code=NAME       encoding of original text
  -t, --to-code=NAME         encoding for output

Output control:
  -c                         omit invalid characters from output

  -s, --silent               suppress warnings
      --verbose              print progress information

  -?, --help                 Give this help list
      --usage                Give a short usage message
  -V, --version              Print program version
"""

def help():
	print """Usage: eyeD3conv [OPTION...] [MP3_FILE...]
Convert encoding of given mp3 files' ID3 tags from one encoding to another.
For example:
	eyeD3conv -f gb2312 -t utf8 -o "%TRACK.%TITLE%.mp3" foo.mp3
convert the id3 tag from gb2312 encoding to utf8 encoding, and rename the file
with the %TRACK%.%TITLE%.mp3 format. Use --usage option for more details."""

def version():
	print "id3conv %s" %  __VERSION__
	print """
Copyright (C) 2006 Kun Xi <kunxi@kunxi.org>
This is free software; released under GPL .  There is NO warranty; not even for
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE."""

def parseOptions(opts, options):
	for o, a in opts:
		if o in ("-f", "--from-code"):
			options["from_enc"] = a
		if o in ("-t", "--to-code"):
			options["to_enc"] = a
		if o == "-c":
			options["omit"] = True
		if o in ("-s", "--silient"):
			options["verbose"] = False
		if o == "--verbose":
			options["verbose"] = True
		if o in ("-?", "--help"):
			help()
			sys.exit(0)
		if o == " --usage":
			usage()
			sys.exit(0)
		if o in ("-V", "--version"):
			version()
			sys.exit(0)

def get(tag, field):
	return apply(getattr(tag, 'get'+field))

def set(tag, field, value):
	return apply(getattr(tag, 'set'+field), [value])

def main():
	pattern = re.compile("%([A-Z]*)%")
	flags = "f:t:co:sv?V"
	long_flags = ["from-code=", "to-code=", "silent",
			"verbose", "help", "usage", "version"]
	try:
		opts, args = getopt.getopt(sys.argv[1:], flags, long_flags)
	except getopt.GetoptError:
		usage()
		sys.exit(1)
	
	options = {
		"from_enc": "iso8859", "to_enc": "utf8",
		"list" : False, "omit": False, "verbose": False }

	parseOptions(opts, options)
	if not args:
		usage()
		sys.exit(1)

	for track in args:
		tag = eyeD3.Tag()
		tag.link(track)
		tag.setVersion([2, 3, 0])
		tag.setTextEncoding(eyeD3.UTF_16_ENCODING)
		if options["verbose"]: print "%s: " % track;
			
		for frame in tag.frames:
			attr = None
			for x in ('text', 'comment'):
				raw = getattr(frame, x, None)
				if raw:
					attr = x
					break
				if raw == None:
					continue

			#encoded = raw.encode("iso8859").decode(options["from_enc"]).encode(options["to_enc"])
			if raw == None or attr == None:
				continue
			try :
				encoded = raw.encode("iso8859").decode(options["from_enc"])
			except UnicodeDecodeError:
				encoded = raw
			if options["verbose"] : print "%s: %s" % (attr, encoded);
			setattr(frame, attr, encoded)
		tag.update()

if __name__ == "__main__":
	main()
