# -*- coding: utf-8 -*-
#
# gPodder - A media aggregator and podcast client
# Copyright (C) 2005-2007 Thomas Perl <thp at perli.net>
#
# gPodder 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 3 of the License, or
# (at your option) any later version.
#
# gPodder 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, see <http://www.gnu.org/licenses/>.
#


#
#  libtagupdate.py -- tag updating/writing library
#  thomas perl <thp@perli.net>   20070315
#
#

# for logging
from liblogger import log

# for tagging of all kinds of filetypes :)
has_mutagen = True
try:
    import mutagen.oggvorbis
    import mutagen.mp3
    from mutagen.easyid3 import EasyID3
except:
    log('(tagupdate) mutagen not found -- tag update disabled')
    has_mutagen = False

# do we provide tagging functions to the user?
def tagging_supported():
    global has_mutagen
    return has_mutagen


tag_update_filetypes = [ 'ogg', 'mp3' ]

def update_metadata_on_file( filename, **metadata):
    global tag_update_filetypes

    ext = filename.split('.')[-1].lower()
    if ext in tag_update_filetypes:
        log('Updating tags for %s', filename)
        if ext == 'ogg':
            file = mutagen.oggvorbis.Open( filename)
            for key in metadata:
                file[key.upper()] = metadata[key]
            file.save()
        if ext == 'mp3':
            file = mutagen.mp3.Open( filename, EasyID3)
            for key in metadata:
                file[key.lower()] = metadata[key]
            # the v1=2 argument adds/updates id3v1 tags to the file, this is
            # useful because mutagen only writes id3v2.4 tags by default which
            # aren't compatible with older [hard|soft]ware (rockbox supports id3v2.4)
            file.save( v1=2)
        return True
    else:
        log('Do not know how to update file extension %s :/', ext)
        return False
