#!/usr/bin/python

# IDv3Tags.py
#       --copyright--                   Copyright 2007 (C) Tranzoa, Co. All rights reserved.    Warranty: You're free and on your own here. This code is not necessarily up-to-date or of public quality.
#       --url--                         http://www.tranzoa.net/tzpython/
#       --email--                       pycode is the name to send to. tranzoa.com is the place to send to.
#       --bodstamps--
#       November 1, 2005        bar
#       November 18, 2007       bar     turn on doxygen
#       November 27, 2007       bar     insert boilerplate copyright
#       May 17, 2008            bar     email adr
#       August 29, 2008         bar     basestring instead of type("") because of unicode strings and others
#       May 27, 2012            bar     doxygen namespace
#       --eodstamps--
##      \file
#       \namespace              tzpython.IDv3Tags
#
#
#       Create IDv3 tags, suitable for writing to the top of an MP3 file.
#
#       Note that this logic does not unsynchronize the data
#
#


import  re



def frame(name, value, is_numeric = False) :
    f   = ""

    if  name and value and (len(name) == 4) and (name[0:1] >= 'A') and (name[0:1] <= 'Z') :
        f   = name

        f  += chr((len(value) >> 21) & 0x7f)
        f  += chr((len(value) >> 14) & 0x7f)
        f  += chr((len(value) >>  7) & 0x7f)
        f  += chr( len(value)        & 0x7f)

        f  += "\000\000"

        if  is_numeric :
            if  isinstance(value, basestring) :
                value  = int(value)
            value     += 0

        f  += value

    return(f)



def create_idv3_tags(song) :
    """
        Take a dictionary with entries like 'title' and convert
        the information to IDv3 tags, suitable for putting at the
        top of an MP3 file.
    """

    tags = ""

    if  song != None :



        frames  = ""

        frames += frame('TIT2', song.get('title',      None))
        frames += frame('TPE1', song.get('artist',     None))
        frames += frame('TPOS', song.get('disc',       None))
        frames += frame('TRCK', song.get('track',      None))
        frames += frame('TALB', song.get('album',      None))
        frames += frame('WOAS', song.get('audio_url',  None))

        v       =               song.get('year',       None)
        if  not v : v = None
        if  isinstance(v, basestring) :
            v   = int(v)
        if  v   :
            v   = "%04u" % v
        frames += frame('TYER', v)

        frames += frame('TCON', song.get('genre',      None))          # should be looked up (#)string if it's in the original list of genres !!!!
        frames += frame('COMM', song.get('comment',    None))

        v       =               song.get('copyright',  "")
        v       = re.sub(r"^[Cc]opyright\s*", "", v)                    # it's assumed
        v       = re.sub(r"^\xa9\s*",         "", v)
        frames += frame('TCOP', v)

        frames += frame('WXXX', song.get('url',        None))

        v       =               song.get('duration',   None)
        if  not v : v = None
        if  isinstance(v, basestring) :
            v   = int(v)
        if  v   :
            v  *= 1000
        if  v :
            frames += frame('TLEN', str(v))

        frames += "\000\000\000\000"

        tlen    = len(frames)


        tags    = "ID3"
        tags   += "\003\000"          # version 3.0

        tags   += "\000"              # flags

        tags   += chr((tlen >> 28) & 0x7f)
        tags   += chr((tlen >> 14) & 0x7f)
        tags   += chr((tlen >>  7) & 0x7f)
        tags   += chr( tlen        & 0x7f)

        tags   += frames

    pass

    return(tags)




if  __name__ == '__main__' :
    import  sys

    if  len(sys.argv) < 2 :

        print   """

--title     name        Set the title.
--album     name        Set the album name.
--artist    name        Set the artist name.

"""

    else :


        def _print(tags) :
            print tags




        import  tzlib
        import  TZCommandLineAtFile

        del(sys.argv[0])

        TZCommandLineAtFile.expand_at_sign_command_line_files(sys.argv)

        song    = {}

        while True :
            oi  = tzlib.array_find(sys.argv, "--title")
            if  oi < 0 :    break
            del sys.argv[oi]
            song['title']   = sys.argv.pop(oi)

        while True :
            oi  = tzlib.array_find(sys.argv, "--album")
            if  oi < 0 :    break
            del sys.argv[oi]
            song['album']   = sys.argv.pop(oi)

        while True :
            oi  = tzlib.array_find(sys.argv, "--artist")
            if  oi < 0 :    break
            del sys.argv[oi]
            song['artist']  = sys.argv.pop(oi)

        pass

        tags = None

        if len(song) > 0 :
            tags = create_idv3_tags(song)
            _print(tags)

        if  len(sys.argv) > 0 :
            import  MusicMetaData

            songs = MusicMetaData.parse_file(sys.argv[0])

            tags  = create_idv3_tags(songs[0])
            _print(tags)

        if  not tags :
            print "Nothing to do!"

        pass

    pass



__ALL__ = [
            'create_idv3_tags'
          ]


#
#
#
# eof
