import web
from decorators import i18n


class Options:
    '''
    This class is a view where the plugins' options are showed to the user.
    Each plugins has a form that can be filled by the user. When a form is
    submitted the corresponding plugin is notified by save_options function.
    '''
    def GET(self, plugin_name):
        pm = web.ctx.plugin_manager

        # If the plugin is enabled
        if plugin_name in (p.name for p in pm.get_enabled_plugins()):
            return web.ctx.render.plugin_manager.options(
                    pm.get_plugin_by_name(plugin_name))

        raise web.notfound()

    @i18n
    def POST(self, plugin_name):
        pm = web.ctx.plugin_manager

        # If the plugin is enabled
        if plugin_name in (p.name for p in pm.get_enabled_plugins()):
            instance = pm.get_plugin_by_name(plugin_name)
            instance.save_options(web.input())
            web.ctx.notify(_('The %s\'s options has been saved' %
                instance.human_name), 'notification')
            raise web.seeother('/pluginmanager')

        raise web.notfound()
