# Copyright (C) 2003 Paramjit Oberoi <param@cs.wisc.edu>
#
# 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, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA

import gtk.glade
import os, os.path
import ConfigParser

def unparse_prefixes(prefixes):
    result = ','.join(prefixes)
    if not result: return ""
    # check for spaces at begin/end and insert extra commas if needed
    if result[0] == " ": result = ","+result
    if result[-1] == " ": result = result + ","
    return result

def parse_prefixes(s):
    prefixes = []
    cur_prefix = ""
    saw_comma = False
    for c in s:
        if c == ",":
            if saw_comma:
                saw_comma = False
                cur_prefix += c
            else:
                saw_comma = True
        else:
            if saw_comma:
                if cur_prefix: prefixes.append(cur_prefix)
                saw_comma = False
                cur_prefix = c
            else:
                cur_prefix += c

    if cur_prefix: prefixes.append(cur_prefix)
    return prefixes

class MoosicAppletConfig:
    def __init__(self, moo, config_file=None):
        self.moo = moo
        self.filename = config_file
        if not self.filename:
            self.filename = os.path.expanduser("~/.moosicappletrc")
            if self.filename[0] == "~": self.filename = ".moosicappletrc"

        self.defaults()
        self.load_file()

    def defaults(self):
        self.display_qlength = True
        self.display_loop = False
        self.width = 150
        self.strip_dir = True
        self.strip_ext = True
        self.replace_underscores = True
        self.strip_prefix = False
        self.prefixes = ["--"," - "]

    def load_file(self):
        c = ConfigParser.ConfigParser()
        c.read(self.filename)
        try: self.display_qlength = c.getboolean("ui","display_qlength")
        except: pass
        try: self.display_loop = c.getboolean("ui","display_loop")
        except: pass
        try: self.width = c.getint("ui","width")
        except: pass
        try: self.strip_dir = c.getboolean("songname","strip_dir")
        except: pass
        try: self.strip_ext = c.getboolean("songname","strip_ext")
        except: pass
        try: self.replace_underscores = c.getboolean("songname","replace_underscores")
        except: pass
        try: self.strip_prefix = c.getboolean("songname","strip_prefix")
        except: pass
        try: self.prefixes = parse_prefixes(c.get("songname","prefixes"))
        except: pass

    def save_file(self):
        c = ConfigParser.ConfigParser()
        c.add_section("ui")
        c.add_section("songname")
        c.set("ui","display_qlength",self.display_qlength)
        c.set("ui","display_loop",self.display_loop)
        c.set("ui","width",self.width)
        c.set("songname","strip_dir",self.strip_dir)
        c.set("songname","strip_ext",self.strip_ext)
        c.set("songname","replace_underscores",self.replace_underscores)
        c.set("songname","strip_prefix",self.strip_prefix)
        c.set("songname","prefixes",unparse_prefixes(self.prefixes))
        c.write(file(self.filename,"w+"))

    def prefs_ui(self):
        # def tmp(*args):
        #     print "tmp called with",len(args),"arguments"
        #     for i in args: print type(i), i

        def on_close_button_clicked(button):
            self.save_file()
            xml.get_widget('prefs_window').destroy()

        def on_display_qlength_toggled(togglebutton):
            self.display_qlength = togglebutton.get_active()
            self.moo.queue_length = None  # to ensure display refresh
            if self.display_qlength:
                self.moo.ui.create_qlength_display()
            else:
                self.moo.ui.destroy_qlength_display()
            self.moo.ui.hbox.show_all()

        def on_display_loop_toggled(togglebutton):
            self.display_loop = togglebutton.get_active()
            self.moo.looping = None  # to ensure display refresh
            if self.display_loop:
                self.moo.ui.create_loop_display()
            else:
                self.moo.ui.destroy_loop_display()
            self.moo.ui.hbox.show_all()

        def on_song_width_value_changed(spinbutton):
            self.width = spinbutton.get_value_as_int()
            self.moo.ui.label.set_size_request(self.width,-1);

        def on_strip_dir_toggled(togglebutton):
            self.strip_dir = togglebutton.get_active()
            self.moo.current_song = None

        def on_strip_ext_toggled(togglebutton):
            self.strip_ext = togglebutton.get_active()
            self.moo.current_song = None

        def on_replace_underscores_toggled(togglebutton):
            self.replace_underscores = togglebutton.get_active()
            self.moo.current_song = None

        def on_strip_prefix_toggled(togglebutton):
            self.strip_prefix = togglebutton.get_active()
            self.moo.current_song = None

        def on_prefixes_changed(gtkentry):
            self.prefixes = parse_prefixes(gtkentry.get_text())
            self.moo.current_song = None

        def on_defaults_button_clicked(button):
            self.defaults()
            load_values_into_ui()
            self.moo.current_song = None

        def load_values_into_ui():
            xml.get_widget('display_qlength').set_active(self.display_qlength)
            xml.get_widget('display_loop').set_active(self.display_loop)
            xml.get_widget('song_width').set_value(self.width)
            xml.get_widget('strip_dir').set_active(self.strip_dir)
            xml.get_widget('strip_ext').set_active(self.strip_ext)
            xml.get_widget('replace_underscores').set_active(self.replace_underscores)
            xml.get_widget('strip_prefix').set_active(self.strip_prefix)
            xml.get_widget('prefixes').set_text(unparse_prefixes(self.prefixes))

        #xml = gtk.glade.XML("<path>/prefs-window.glade")

        # The following magic depends on Fredrik Lundh's "squeezeTool" -- all files
        # required for the applet are packaged up into just one file at build time.
        # __main__.open() returns a stringIO file object

        import __main__
        s = __main__.open("prefs-window.glade").read()
        xml = gtk.glade.xml_new_from_buffer(s,len(s))

        xml.signal_autoconnect(locals())
        load_values_into_ui()

        xml.get_widget('close_button').grab_focus()
        xml.get_widget('close_button').grab_default()

