#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright (C) 2010 Matteo Castellini <self {at} mcastellini [dot] net>
#
# This program 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 2 of the License, or
# (at your option) any later version.
#
# This program 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/>.

from mutagen import File
import re
import sys
from optparse import OptionParser
from os.path import realpath, isdir, join
from os import listdir

usage = '%prog [OPTION]... FILE...'
version = '%prog 0.1'
parser = OptionParser(usage=usage, version=version, prog='d2_cleaner')
parser.add_option("-b", "--basetags", metavar="BASE_NAMES", dest="basetags",
        default="artist,album", help="indicate the tags whose variations you "
        "would like to remove separated by a comma (default: %default)")
parser.add_option("-l", "--list", metavar="FILE", dest="list", default="",
        help="read filenames from a list (from either FILE or STDIN (-))")
parser.add_option("-r", "--recursive", dest="recursive", action="store_true", 
        default=False, help="descend recursively into directories")
parser.add_option("-s", "--separator", metavar="CHAR", dest="separator",
        default=",", help="change the tags list separator (default: %default)")
parser.add_option("-t", "--tagslist", metavar="TAGS_LIST", dest="tagslist",
        default="", help="indicate a list of tags that you would like to "
        "remove separated by a comma (default: %default)")
(opts, args) = parser.parse_args()

def clean(audio_file, patterns):
    save = False
    for tag_name in audio_file.keys():
        for pattern in patterns:
            if pattern.match(tag_name):
                del audio_file[tag_name]
                save = True
    else:
        return save, audio_file

if __name__ == '__main__':
    file_list = []
    if opts.list:
        if opts.list == '-':
            file_list.extend(sys.stdin.read().splitlines())
        else:
            try:
                stream = open(opts.list, 'r')
                file_list.extend(stream.readlines())
                stream.close()
            except IOError as (errno, strerror):
                print "%s: cannot open '%s': %s" % (parser.prog, opts.list,
                        strerror)
                sys.exit(1)
    elif not args or args[0] == '-':
        file_list.append(sys.stdin.read().strip())
    else:
        file_list.extend(args)

    if opts.recursive:
        for filename in file_list:
            filename = realpath(filename)
            if isdir(filename):
                file_list.extend([join(filename, n) for n in listdir(filename) 
                    if join(filename, n) not in file_list])

    patterns = []
    if opts.basetags:
        patterns.append(re.compile('^(%s)\s?\w+$' % 
            ('|'.join(opts.basetags.strip().split(opts.separator))), re.I))
    if opts.tagslist:
        patterns.append(re.compile('^(%s)$' %
            ('|'.join(opts.tagslist.strip().split(opts.separator))), re.I))

    for name in file_list:
        try:
            audio = File(name)
        except IOError as (errno, strerror):
            print "%s: cannot open '%s': %s" % (parser.prog, name, strerror)
        else:
            print "Processing '%s'..." % realpath(name), 
            if not audio:
                print "Not an audio file."
            else:
                audio = clean(audio, patterns)
                if audio[0]:
                    audio[1].save()
                    print "OK."
                else:
                    print "No change needed."
    else:
        sys.exit(0)

