#!/usr/bin/env python2

try:
    import pygtk
    pygtk.require('2.0')
    import gtk
    _GTK = True
except:
    _GTK = False
    print ("Warning: GTK UI is not available")

import os
import argparse
from mutagen.id3 import TALB, TCMP
from mutagen.mp3 import MP3

class Mp3ficker():
    def __init__(self, base_path, compilation):
        self.base_path = base_path
        self.compilation = compilation

    def find_mp3s(self):
        self.mp3s = []
        for root, dirs, files in os.walk(self.base_path):
            for f in  files:
                filename = root + "/" + f
                if os.path.isfile(filename) and (filename[-3:] == "mp3" or filename[-3:] == "MP3"):
                    self.mp3s.append(os.path.realpath(filename))

    def print_mp3s(self):
        print (self.mp3s)

    def ficken(self):
        for mp3 in self.mp3s:
            d = os.path.dirname(mp3)
            new_dir = d[d.rfind('/') + 1:]
            if not len(new_dir):
                continue
            mm = MP3(mp3)
            print ("ficking \"" + mp3 + "\" new album name " + new_dir)
            if mm.has_key("TALB"):
                print (mm.get("TALB"))
                mm["TALB"] = TALB(encoding=3, text=new_dir)
                if self.compilation == True:
                    mm["TCMP"] = TCMP(encoding=3, text=u"1")
            else:
                print "TALB missing"
                mm["TALB"] = TALB(encoding=3, text=new_dir)
                if self.compilation == True:
                    mm["TCMP"] = TCMP(encoding=3, text=u"1")
            mm.save()

if _GTK == True:
    class UiFicker(gtk.Window):
        def __init__(self, base_path, comp, parent=None):
            self.base_path = base_path
            self.compilation = comp

            gtk.Window.__init__(self)
            try:
                self.set_screen(parent.get_screen())
            except AttributeError:
                self.connect('destroy', lambda *w: gtk.main_quit())
            self.set_size_request(400, 100)

            label = gtk.Label("Directory:")
            self.entry = gtk.Entry()
            self.entry.set_text(self.base_path)
            self.ck_compilation = gtk.CheckButton("compilation")
            self.ck_compilation.set_active(self.compilation)
            self.ck_compilation.connect("clicked", self.clicked_ck_compilation)
            self.bt_add = gtk.Button("add")
            self.bt_add.connect("clicked", self.clicked_bt_add)
            self.bt_ficken = gtk.Button("ficken")
            self.bt_ficken.connect("clicked", self.clicked_bt_ficken)

            hbox = gtk.HBox(False, 10)
            hbox.pack_start(self.ck_compilation, True, True, 0)
            hbox.pack_start(self.bt_add, False, True, 0)
            hbox.pack_start(self.bt_ficken, False, True, 0)

            vbox = gtk.VBox(False, 10)
            vbox.pack_start(label, True, True, 0)
            vbox.pack_start(self.entry, True, True, 0)
            vbox.pack_start(hbox, False, True, 0)

            self.add(vbox)
            self.show_all()

        def clicked_bt_add(self, button):
            dialog = gtk.FileChooserDialog("Choose directroy", None,
                        gtk.FILE_CHOOSER_ACTION_SELECT_FOLDER,
                        (gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL,
                         gtk.STOCK_OK, gtk.RESPONSE_OK))
            response = dialog.run()
            if response == gtk.RESPONSE_OK:
                directory = dialog.get_filename()
                print ("directory: " + directory)
                self.entry.set_text(directory)
            dialog.destroy()

        def clicked_ck_compilation(self, button):
            state = button.get_active()
            print ("compilation: " + str(state))
            if state == True:
                self.compilation = True
            else:
                self.compilation = False

        def clicked_bt_ficken(self, button):
            self.base_path = self.entry.get_text()
            if not os.path.isdir(self.base_path):
                err = gtk.MessageDialog(None, 0, gtk.MESSAGE_ERROR,
                        gtk.BUTTONS_OK, "Invalid folder: " + self.base_path)
                err.run()
                err.destroy()

            try:
                ficker = Mp3ficker(self.base_path, self.compilation)
                ficker.find_mp3s()
                ficker.ficken()
            except:
                err = gtk.MessageDialog(None, 0, gtk.MESSAGE_ERROR,
                        gtk.BUTTONS_OK, "Failed to fick mp3s")
                err.run()
                err.destroy()


def main():
    parser = argparse.ArgumentParser(description = "mp3ficker - the ultimate mp3 tool")
    if _GTK == True:
        parser.add_argument('--ui', action='store_true', help='use GTK user interface')
    parser.add_argument('--comp', action='store_true', help='set compilation field for iTunes')
    parser.add_argument('--wd', nargs=1, type=str, help='set base path to start from')

    options = parser.parse_args()
    print (options)

    if options.wd:
        base_path = options.wd[0]
    else:
        base_path = os.getcwd()

    if _GTK == True and options.ui == True:
        ui = UiFicker(base_path, options.comp)
        gtk.main()
    else:
        fick = Mp3ficker(base_path, options.comp)
        fick.find_mp3s()
        fick.ficken()

if __name__ == '__main__':
    main()

# vim: sw=4 ts=4 expandtab
