#!/usr/bin/python2
# -*- coding: ISO-8859-1 -*-
# Copyright (C) 2003-2006 J. David Ibez <jdavid@itaapy.com>
#
# 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., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.

# Import from the Standard Library
from optparse import OptionParser
import sys

# Import from itools
import itools
from itools.resources import get_resource
from itools.gettext import PO
from itools.xhtml import XHTML
import itools.stl
from itools.handlers.python import Python



if __name__ == '__main__':
    version = 'itools %s' % itools.__version__
    description = ('Extracts the translatable messages from the given source'
                   ' files. Builds a PO file with these messages, and prints'
                   ' to the standard output.')
    parser = OptionParser('%prog [OPTIONS] [<file>...]',
                          version=version, description=description)

    parser.add_option('-o', '--output',
                      help="The output will be written to the given file,"
                           " instead of printed to the standard output.")

    options, args = parser.parse_args()

    if options.output is None:
        output = sys.stdout
    else:
        output = open(options.output, 'w')

    try:
        po = PO.PO()
        for source_file in args:
            # Load the source handler
            resource = get_resource(source_file)
            if source_file.endswith('.py'):
                handler = Python(resource)
            else:
                # XXX Suppose it is XHTML
                handler = XHTML.Document(resource)
            # Extract the messages
            for msgid, line_number in handler.get_messages():
                po.set_message(msgid, references={source_file: [line_number]})

        # XXX Should omit the header?
        output.write(po.to_str())
    finally:
        if options.output is not None:
            output.close()
