1# -*- coding: utf-8 -*-
2
3# Copyright(C) 2010-2011 Christophe Benz, Romain Bignon
4#
5# This file is part of weboob.
6#
7# weboob is free software: you can redistribute it and/or modify
8# it under the terms of the GNU Lesser General Public License as published by
9# the Free Software Foundation, either version 3 of the License, or
10# (at your option) any later version.
11#
12# weboob is distributed in the hope that it will be useful,
13# but WITHOUT ANY WARRANTY; without even the implied warranty of
14# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15# GNU Lesser General Public License for more details.
16#
17# You should have received a copy of the GNU Lesser General Public License
18# along with weboob. If not, see <http://www.gnu.org/licenses/>.
19
20
21__all__ = ['FormattersLoader', 'FormatterLoadError']
22
23
24class FormatterLoadError(Exception):
25    pass
26
27
28class FormattersLoader(object):
29    BUILTINS = ['htmltable', 'multiline', 'simple', 'table', 'csv', 'webkit', 'json', 'json_line']
30
31    def __init__(self):
32        self.formatters = {}
33
34    def register_formatter(self, name, klass):
35        self.formatters[name] = klass
36
37    def get_available_formatters(self):
38        l = set(self.formatters)
39        l = l.union(self.BUILTINS)
40        l = sorted(l)
41        return l
42
43    def build_formatter(self, name):
44        if name not in self.formatters:
45            try:
46                self.formatters[name] = self.load_builtin_formatter(name)
47            except ImportError as e:
48                FormattersLoader.BUILTINS.remove(name)
49                raise FormatterLoadError('Unable to load formatter "%s": %s' % (name, e))
50        return self.formatters[name]()
51
52    def load_builtin_formatter(self, name):
53        if name not in self.BUILTINS:
54            raise FormatterLoadError('Formatter "%s" does not exist' % name)
55
56        if name == 'htmltable':
57            from .table import HTMLTableFormatter
58            return HTMLTableFormatter
59        elif name == 'table':
60            from .table import TableFormatter
61            return TableFormatter
62        elif name == 'simple':
63            from .simple import SimpleFormatter
64            return SimpleFormatter
65        elif name == 'multiline':
66            from .multiline import MultilineFormatter
67            return MultilineFormatter
68        elif name == 'webkit':
69            from .webkit import WebkitGtkFormatter
70            return WebkitGtkFormatter
71        elif name == 'csv':
72            from .csv import CSVFormatter
73            return CSVFormatter
74        elif name == 'json':
75            from .json import JsonFormatter
76            return JsonFormatter
77        elif name == 'json_line':
78            from .json import JsonLineFormatter
79            return JsonLineFormatter
80