#!/usr/bin/env python

# Authors:
#   David Green <david4dev@gmail.com>
#
# Sound Theme Manager: Software to manage freedesktop.org sound themes.
# Copyright (C) 2011 David Green <david4dev@gmail.com>
#
# This file is part of `Sound Theme Manager`.
#
# `Sound Theme Manager` 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.
#
# `Sound Theme Manager` 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 `Sound Theme Manager`.  If not, see <http://www.gnu.org/licenses/>.
import sys
sys.path.append('/usr/share/pyshared')

from soundtheme import SoundTheme
import gtk
import os
import gettext
gettext.bindtextdomain('sound-theme-manager')
_ = gettext.gettext

class ActionButton(gtk.Button):
    def __init__(self, parent, action):
        super(ActionButton, self).__init__()
        self.prnt = parent
        self.action = action
        self.icon = gtk.Image()
        self.icon.set_from_file(
            self.prnt.__class__.image_path(self.action)
        )
        self.icon.show()
        self.add(self.icon)
        self.connect("clicked", self.on_click)
        self.show()

    def message(self, msg=None):
        if isinstance(msg, dict):
            md = gtk.MessageDialog(
                self.prnt,
                gtk.DIALOG_DESTROY_WITH_PARENT,
                msg.has_key('type') and msg['type'] or gtk.MESSAGE_INFO,
                gtk.BUTTONS_CLOSE
            )
            md.set_markup(msg['markup'])
            md.run()
            md.destroy()

    def on_click(self, w):
        self.message(self.prnt.__class__.actions[self.action](
            self,
            self.prnt.current_theme()
        ))

class ActionButtonBar(gtk.HBox):
    def __init__(self, parent, *actions):
        super(ActionButtonBar, self).__init__()
        self.prnt = parent
        self.actions = []
        self.buttons = []
        for a in actions:
            self.actions.append(a)
            b = ActionButton(self.prnt, a)
            self.buttons.append(b)
            self.add(b)
        self.show()

class SoundThemeSelector(gtk.HBox):
    def __init__(self):
        cls = self.__class__
        super(cls, self).__init__()
        self.box = gtk.combo_box_new_text()
        self.themes = []
        self.reset()
        self.box.show()
        self.add(self.box)
        self.show()
        self.on_change = lambda theme: None
        self.box.connect('changed', self.changed)

    def reset(self):
        i = len(self.themes)
        while i > 0:
            i -= 1
            self.box.remove_text(i)
        self.themes = []
        for thm in SoundTheme.user_themes():
            theme = SoundTheme(thm)
            if not (theme.data.has_key('hidden') and theme.data['hidden']):
                self.themes.append(theme)
        self.current = SoundTheme.current()
        i = 0
        current_index = 0
        for theme in self.themes:
            localename = theme.get_locale_name()
            if theme.name  == self.current:
                current_index = i
                localename = '* ' + theme.get_locale_name()
            self.box.append_text(localename)
            i += 1
        self.box.set_active(current_index)
        return self

    def current_theme(self):
        return self.themes[self.box.get_active()]

    def changed(self, w):
        self.on_change(self.current_theme())

class SoundSelector(gtk.HBox):
    def __init__(self, theme, inv=False):
        cls = self.__class__
        super(cls, self).__init__()
        self.box = gtk.combo_box_new_text()
        self.theme = theme
        self.inv = inv
        self.sounds = []
        self.reset()
        self.box.show()
        self.add(self.box)
        self.show()
        self.on_change = lambda sound: None
        self.box.connect('changed', self.changed)

    def reset(self, theme=None):
        if theme:
            self.theme = theme
        i = len(self.sounds)
        while i > 0:
            i -= 1
            self.box.remove_text(i)
        self.sounds = list(self.inv and self.theme.inverse_list_sounds() or self.theme.list_sounds())
        for sound in self.sounds:
            self.box.append_text(_(' '.join(sound.split('-'))))
        self.box.set_active(0)
        return self

    def current_sound(self):
        return self.sounds[self.box.get_active()]

    def play(self):
        self.theme.play(self.current_sound())

    def changed(self, w):
        self.on_change(self.current_sound())

class AddSoundDialog(gtk.Window):
    def __init__(self, theme, callback=lambda name,path:None):
        super(AddSoundDialog, self).__init__()
        self.theme = theme
        self.callback = callback
        self.add_widgets()
        self.connect_events()
        self.set_title(_('Select a sound to add.'))
        self.show()
        self.on_change()

    def add_widgets(self):
        self.selector = SoundSelector(self.theme, True)
        self.button = gtk.Button()
        self.button_label = gtk.Label(_('ok'))
        self.button.add(self.button_label)
        self.button.show()
        self.button_label.show()
        self.selector.add(self.button)
        self.help_label = gtk.Label(_('Select a sound to add.'))
        self.help_label.show()
        self.container = gtk.VBox()
        self.container.show()
        self.container.add(self.selector)
        self.container.add(self.help_label)
        self.add(self.container)

    def connect_events(self):
        self.button.connect('clicked', self.on_ok)
        self.selector.on_change = self.on_change

    def on_ok(self, w=None):
        sound = self.selector.current_sound()
        self.callback(sound)

    def on_change(self, w=None):
        t = _(SoundTheme.sound_names[self.selector.current_sound()])
        i = 0
        s = ''
        for c in t:
            s += c
            if i > 50 and c == ' ':
                i = 0
                s += "\n"
            i += 1
        self.help_label.set_text(s)

class AddThemeDialog(gtk.Window):
    def __init__(self, fn=lambda:None):
        self.fn = fn
        super(AddThemeDialog, self).__init__()
        self.set_title(_("Enter the name for your new theme."))
        self.entry = gtk.Entry()
        self.button = gtk.Button()
        self.label = gtk.Label(_("ok"))
        self.container = gtk.HBox()
        self.button.add(self.label)
        self.container.add(self.entry)
        self.container.add(self.button)
        self.add(self.container)
        self.label.show()
        self.button.show()
        self.entry.show()
        self.container.show()
        self.button.connect('clicked', self.on_ok)
        self.show()

    def on_ok(self, *a):
        SoundTheme.create(self.entry.get_text())
        self.fn()
        self.destroy()

class LocaleSelector(gtk.HBox):
    @classmethod
    def locales(cls):
        yield _("Default")
        for l in os.listdir('/usr/share/locale'):
            if os.path.isdir(os.path.join('/usr/share/locale', l)):
                yield l

    def __init__(self):
        super(LocaleSelector, self).__init__()
        self.on_change = lambda l:None
        self.locales = list(self.__class__.locales())
        self.box = gtk.combo_box_new_text()
        self.add(self.box)
        for l in self.locales:
            self.box.append_text(l)
        self.box.set_active(0)
        self.box.show()
        self.box.connect('changed', self.changed)
        self.show()

    def current_locale(self):
        return self.locales[self.box.get_active()]

    def changed(self, *a):
        self.on_change(self.current_locale())

class EditThemeDialog(gtk.Window):
    def __init__(self, theme):
        self.theme = theme
        super(EditThemeDialog, self).__init__()
        self.widget = {}
        self.add_widgets()
        self.connect_events()
        self.update()
        self.show()

    def add_widget(self, name, widget, parent='container'):
        self.widget[name] = widget
        widget.show()
        self.widget[parent].add(widget)

    def add_widgets(self):
        self.widget = {}
        self.widget['container'] = gtk.VBox()
        self.widget['container'].show()
        self.add(self.widget['container'])

        self.add_widget('locale', gtk.HBox())
        self.add_widget('locale_label', gtk.Label(_("Language: ")), 'locale')
        self.add_widget('locale_selector', LocaleSelector(), 'locale')

        self.add_widget('name', gtk.HBox())
        self.add_widget('name_label', gtk.Label(_("Name: ")), 'name')
        self.add_widget('name_entry', gtk.Entry(), 'name')

        self.add_widget('comment', gtk.HBox())
        self.add_widget('comment_label', gtk.Label(_("Description: ")), 'comment')
        self.add_widget('comment_entry', gtk.Entry(), 'comment')

        self.add_widget('inherits', gtk.HBox())
        self.add_widget('inherits_label', gtk.Label(_("Fallback Themes (separate by a comma): ")), 'inherits')
        self.add_widget('inherits_entry', gtk.Entry(), 'inherits')

        self.add_widget('example', gtk.HBox())
        self.add_widget('example_label', gtk.Label(_("Example Sound: ")), 'example')
        self.add_widget('example_selector', SoundSelector(self.theme), 'example')

        self.add_widget('hidden', gtk.HBox())
        self.add_widget('hidden_label', gtk.Label(_("Hide Theme?: ")), 'hidden')
        self.add_widget('hidden_checkbox', gtk.CheckButton(), 'hidden')

    def connect_events(self):
        self.connect('delete-event', self.delete_event)
        self.connect('unmap-event', self.save)
        self.widget['locale_selector'].on_change = self.locale_changed
        self.widget['locale_selector'].box.connect('focus-in-event', self.changed)
        for name in  ['name_entry','comment_entry','inherits_entry']:
            self.widget[name].connect('changed', self.changed)
        self.widget['example_selector'].box.connect('changed', self.changed)

    def update(self):
        locale = None
        if self.widget['locale_selector'].current_locale() != _("Default"):
            locale = self.widget['locale_selector'].current_locale()
        name = ''
        try:
            name = self.theme.get_name(locale)
        except:
            pass
        comment = ''
        try:
            comment = self.theme.get_comment(locale)
        except:
            pass
        inherits = []
        try:
            inherits = self.theme.get_inherits()
        except:
            pass
        example = 'desktop-login'
        try:
            example = self.theme.get_example()
        except:
            pass
        hidden = False
        try:
            hidden = self.theme.get_hidden()
        except:
            pass
        self.widget['name_entry'].set_text(name)
        self.widget['comment_entry'].set_text(comment)
        self.widget['inherits_entry'].set_text(','.join(inherits))
        self.widget['example_selector'].box.set_active(self.widget['example_selector'].sounds.index(example))
        self.widget['hidden_checkbox'].set_active(hidden)

    def changed(self, *a):
        locale = None
        if self.widget['locale_selector'].current_locale() != _("Default"):
            locale = self.widget['locale_selector'].current_locale()
        self._locale = locale
        self.theme.set_name(self.widget['name_entry'].get_text(), locale)
        self.theme.set_comment(self.widget['comment_entry'].get_text(), locale)
        self.theme.set_inherits(*(self.widget['inherits_entry'].get_text().split(',')))
        self.theme.set_example(self.widget['example_selector'].current_sound())
        self.theme.set_hidden(self.widget['hidden_checkbox'].get_active())

    def locale_changed(self, *a):
        self.theme.add_locale(self.widget['locale_selector'].current_locale())
        self.update()
        self.changed()

    def save(self, *a):
        self.changed()
        self.theme.save()

    def delete_event(self, *a):
        self.save()
        self.destroy()
        return False

class SoundThemeInstallDialog(object):
    dialog = gtk.FileChooserDialog(
        title = _('Choose a sound theme package to install.'),
        action=gtk.FILE_CHOOSER_ACTION_OPEN,
        buttons=(gtk.STOCK_OPEN, 1, gtk.STOCK_CANCEL, 0)
    )

    @classmethod
    def run(cls):
        if cls.dialog.run() == 1:
            r = cls.dialog.get_filename()
        else:
            r = False
        cls.dialog.hide()
        return r

    @classmethod
    def installed(cls, success=True):
        if success:
            return (_("Installed theme <i>%s</i> successfully.") % cls.dialog.get_filename())
        else:
            return (_("Couldn't install <i>%s</i>.") % cls.dialog.get_filename())

class SoundThemeManager(gtk.Window):
    actions = {
        'set' : lambda button,theme: theme.set() and {
                'markup': _('Sound theme set to <i>%s</i>.') %
                theme.get_locale_name(),
                'bypassing-pythons-crappy-lambdas' : button.prnt.widget['theme_selector'].reset()
            } or {
                'type' : gtk.MESSAGE_ERROR,
                'markup': 'Failed to set sound theme.'
            },
        'remove' : lambda button,theme: SoundTheme.remove(theme.name) and {
                'markup': _('Sound theme <i>%s</i> removed.') %
                theme.get_locale_name(),
                'bypassing-pythons-crappy-lambdas' : button.prnt.widget['theme_selector'].reset()
            } or {
                'type' : gtk.MESSAGE_ERROR,
                'markup': 'Failed to remove sound theme.'
            },
        'package' : lambda button,theme: theme.package() and {
                'markup': _('Package created: %s') %
                ('<i>'+os.path.abspath(theme.package_path)+'</i>')
            } or {
                'type' : gtk.MESSAGE_ERROR,
                'markup': 'Failed to package sound theme.'
            },
        'install' : lambda button,theme: SoundTheme.install(SoundThemeInstallDialog().run()) and {
            'markup' : SoundThemeInstallDialog().installed(),
            'bypassing-pythons-crappy-lambdas' : button.prnt.widget['theme_selector'].reset()
        } or {
            'markup' : SoundThemeInstallDialog().installed(False),
            'type' : gtk.MESSAGE_ERROR
        },
        'preview' : lambda button,theme: theme.play_preview(),
        'play' : lambda button,theme: button.prnt.widget['sound_selector'].play(),
        'audacity' : lambda button,theme: theme.edit_sound(button.prnt.current_sound()) or {
            'type' : gtk.MESSAGE_ERROR,
            'markup' : _("Couldn't open Audacity. You need to have Audacity installed for this to work.")
        },
        'add' : lambda button,theme: AddSoundDialog(theme, lambda name: button.prnt.set_sound(theme, name)),
        'removesound' : lambda button,theme: theme.remove_sound(button.prnt.current_sound()) and {
            'bpcl' : theme.save(),
            'bypassing-pythons-crappy-lambdas' : button.prnt.widget['theme_selector'].reset(),
            'markup' : _("Removed sound successfully."),
            'type' : gtk.MESSAGE_INFO
        } or {
            'markup' : _("Failed to remove sound."),
            'type' : gtk.MESSAGE_ERROR
        },
        'change' : lambda button,theme:button.prnt.set_sound(theme, button.prnt.current_sound()),
        'new' : lambda button,theme: AddThemeDialog(lambda:button.prnt.widget['theme_selector'].reset()),
        'edit' : lambda button,theme:EditThemeDialog(theme)
    }
    help_text = {
        'default':[_("Welcome to Sound Theme Manager."),_("Hover your cursor over something to view help for that item.")],
        'theme_selector':[_("Use this drop down menu to select an installed sound theme."),_("The '*' indicates the current sound theme.")],
        'sound_selector':[_("Use this drop down menu to select a sound from the selected sound theme.")],
        'set_button' : [_("Click on this button to set the selected sound theme as your current sound theme.")],
        'remove_button' : [_("Click on this button to remove the selected sound theme."),_("To use a removed sound theme again you will need to reinstall it."),_("This will only delete the sound theme from your user account."),_("If the sound theme is installed for all users it will reappear next time you open this program.")],
        'package_button' : [_("Click on this button to create an installable sound theme package from the selected theme."),_("The file that is created can be installed from this program using the install button.")],
        'install_button' : [_("Click on this button to install a sound theme from a sound theme package."),_("The theme will be installed only in your user account."),_("Once installed it will be available from the drop down menu.")],
        'preview_button' : [_("Click on this button to play a preview sound from the selected sound theme.")],
        'play_button' : [_("Click to play this sound.")],
        'audacity_button' : [_("Click to open this sound in Audacity.")],
        'add_button' : [_("Click to add a sound to this theme.")],
        'removesound_button' : [_("Click to remove this sound from the selected theme.")],
        'change_button' : [_("Click to change the selected sound to play a sound from a file."), _("The file must be an OGG Vorbis or WAV file.")],
        'new_button' : [_("Click to create a new sound theme.")],
        'edit_button' : [_("Click to edit the metadata of the current theme (name, description etc).")]
    }

    @classmethod
    def image_path(cls, name):
        user_path = os.path.join(os.environ['HOME'], '.sound-theme-manager/images', name + '.svg')
        system_path = os.path.join('/usr/share/sound-theme-manager/images', name + '.svg')
        testing_path = os.path.join('./images', name + '.svg')
        if os.path.exists(testing_path):
            return testing_path
        elif os.path.exists(user_path):
            return user_path
        elif os.path.exists(system_path):
            return system_path
        else:
            return None

    def __init__(self):
        super(SoundThemeManager, self).__init__()
        self.set_window_properties()
        self.add_widgets()
        self.display_help()
        self.add_help_to_widgets()
        self.connect_events()
        self.show_all()

    def current_theme(self):
        return self.widget['theme_selector'].current_theme()

    def current_sound(self):
        return self.widget['sound_selector'].current_sound()

    def set_sound(self, theme, sound):
        dialog = gtk.FileChooserDialog(
            title = _("Choose a sound file to use as '%s'.") % sound,
            action=gtk.FILE_CHOOSER_ACTION_OPEN,
            buttons=(gtk.STOCK_OPEN, 1, gtk.STOCK_CANCEL, 0)
        )
        if dialog.run() == 1:
            path = dialog.get_filename()
            dialog.destroy()
            m = ''
            t = None
            if theme.set_sound(sound, path):
                theme.save()
                t = gtk.MESSAGE_INFO
                m = _("Sound <b>%s</b> set to file <i>%s</i> successfully.") % (sound, path)
            else:
                t = gtk.MESSAGE_ERROR
                m = _("Failed to set sound <b>%s</b> to file <i>%s</i>.\n\nMake sure that it is a <i>.oga</i>, <i>.wav</i> or <i>.ogg</i> file.") % (sound, path)
            self.widget['theme_selector'].reset()
            self.widget['sound_selector'].reset()
            md = gtk.MessageDialog(
                self,
                gtk.DIALOG_DESTROY_WITH_PARENT,
                t,
                gtk.BUTTONS_CLOSE
            )
            md.set_markup(m)
            md.run()
            md.destroy()

    def display_help(self, string=None):
        s = ''
        if string:
            s = ''.join(self.__class__.help_text[string])
        else:
            s = _("Theme Description:") + ' ' + self.current_theme().get_locale_comment() + "\n\n" + _("Sound Description:") + ' ' + _(SoundTheme.sound_names[self.current_sound()])
        while len(s) < 500:
            s += ' '
        h = "\n\n"
        i = 0
        for c in s:
            h += c
            if i >= 50 and (c == '.' or c == ' '):
                h += "\n"
                i = 0
            elif c == '.':
                h += ' '
            i += 1

        self.widget['help_label'].set_text(
            h
        )

    def add_help_to_widget(self, widget, string):
        widget.connect("enter-notify-event", lambda w,e:self.display_help(string))
        widget.connect("focus-in-event", lambda w,e:self.display_help(string))
        widget.connect("leave-notify-event", lambda w,e:self.display_help())
        widget.connect("focus-out-event", lambda w,e:self.display_help())

    def add_widget(self, name, widget, parent='container'):
        self.widget[name] = widget
        widget.show()
        self.widget[parent].add(widget)

    def add_widgets(self):
        self.widget = {}
        self.widget['container'] = gtk.VBox()
        self.widget['container'].show()
        self.add(self.widget['container'])

        self.add_widget('theme', gtk.HBox())
        self.add_widget('theme_label', gtk.Label(_('Theme: ')), 'theme')
        self.add_widget('theme_selector', SoundThemeSelector(), 'theme')
        self.add_widget(
            'theme_buttons',
            ActionButtonBar(
                self, 'preview', 'set', 'remove', 'package', 'install',
                'new', 'edit'
            ),
            'theme'
        )

        self.add_widget('sound', gtk.HBox())
        self.add_widget('sound_label', gtk.Label(_('Sound: ')), 'sound')
        self.add_widget(
            'sound_selector',
            SoundSelector(
                self.widget['theme_selector'].current_theme(),
                False
            ),
            'sound'
        )
        self.add_widget(
            'sound_buttons',
            ActionButtonBar(
                self, 'play', 'audacity', 'add', 'removesound', 'change'
            ),
            'sound'
        )

        self.add_widget('help', gtk.HBox())
        #self.add_widget(
        #    'help_button',
        #    ActionButton(self, 'help'),
        #    'help'
        #)
        self.add_widget('help_label', gtk.Label(), 'help')

    def add_help_to_widgets(self):
        self.add_help_to_widget(
            self.widget['theme_selector'].box,
            'theme_selector'
        )
        self.add_help_to_widget(
            self.widget['sound_selector'].box,
            'sound_selector'
        )
        for b in (self.widget['theme_buttons'].buttons + self.widget['sound_buttons'].buttons):
            self.add_help_to_widget(
                b,
                b.action + '_button'
            )

    def set_window_properties(self):
        self.set_title(_("Sound Theme Manager"))
        self.resize(400, 200)
        self.set_icon_from_file(self.__class__.image_path("sound-theme-manager"))

    def connect_events(self):
        self.connect("delete_event", self.delete_event)
        self.connect("destroy", self.destroy)
        self.widget['theme_selector'].on_change = lambda t:self.widget['sound_selector'].reset(t) and self.display_help()
        self.widget['sound_selector'].on_change = lambda t:self.display_help()

    def destroy(self, widget, data=None):
        gtk.main_quit()

    def delete_event(self, widget, event, data=None):
        return False

    def main(self):
        gtk.main()

SoundThemeManager().main()
