#!/usr/bin/env python

# this is a very old script written by Kun Xi on 2007 https://www.kunxi.org/2008/02/id3-tag-for-programmers/
# I made a few changes back in 2010 
# today I downloaded one greek group's 3 albums where the mp3 tags were in greek cp1353 codepage.
# So this is the new   eyed3conv tailored for python 3 .
# Now all the tags text are saved as utf-8 
# so IF YOU HAVE TO SPECIFY ENCODING it will be -t (to) (it is a misconception but i dont't have time) 
#    
# so in my case (greek tags) it is :
# eyed3conv  -f iso-8859-1 -t cp1253 file.mp3 (this is the default now if you omit -f and -t)
# 
# i believe always in problematic mp3 tags encoding is latin , iso-8859-1 and you 
# have to guess the representation.
# it would be nice if someone sent some mp3 with chinese tags etc so we can test 
# email is admin@kaotonik.net

__AUTHORS__ = ["Kun Xi" ,"Thimios Katsoulis"]
__VERSION__ = "0.2"
__LICENSE__ = "GPL"

import getopt, sys, re, os
import eyed3
from eyed3 import id3
from eyed3.id3 import  frames
 

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  -t gb2312 -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 - 2020 Kun Xi <kunxi@kunxi.org> , Thimios Katsoulis <thk@kaotonik.net>
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 trans(v ,options):
     
    vb = bytes(v,options['from_enc'])
    vbs = vb.decode(options['to_enc'])
     
    return vbs

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": "iso-8859-1", "to_enc": "cp1253","list" : False, "omit": False, "verbose": False }
    parseOptions(opts, options)
    #print (str(options))
    if not args:
        usage()
        sys.exit(1)
        
   
    eyed3.log.setLevel("ERROR")

    fids = [frames.TITLE_FID , frames.ARTIST_FID , frames.ALBUM_FID]
    for track in args:
        tag = id3.Tag()         
        tag.parse(track)   
        print ("--- " + track + " ---")           
        for fid in fids:             
            v = tag.getTextFrame(fid) 
            if v: 
                try:
                    nv =trans(v,options)
                    print (v +  " --> " + nv)     
                    tag.setTextFrame(fid ,trans(v,options))
                except:
                    print ("could not transform " + fid.decode('utf-8') + " , " + v + " . Maybe it is already transformed"  )       
        if len(tag.lyrics)>0:       
            v = tag.lyrics[0].text 
            if v:
                try:
                    nv= trans(v , options)  
                    print (v +  " --> " + nv)           
                    tag.lyrics[0].text = nv
                except:
                    print ("could not transform lyrics " +  " , " + v  + " . Maybe it is already transformed")   
        tag.save(encoding='utf-8')
        
if __name__ == "__main__":
    main()
