#!/usr/bin/env python
# encoding=UTF-8

# Copyright © 2008-2015 Jakub Wilk <jwilk@jwilk.net>
#
# This file is part of djvusmooth.
#
# djvusmooth is free software; you can redistribute it and/or modify it
# under the terms of the GNU General Public License version 2 as published
# by the Free Software Foundation.
#
# djvusmooth 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.

from __future__ import print_function

if __name__ != '__main__':
    raise ImportError('This module is not intended for import')

import argparse
import sys

import djvu.decode
import djvu.sexpr

from djvusmooth.text.mangle import import_, export

def do_export(djvu_file_name, page_no):
    context = djvu.decode.Context()
    document = context.new_document(djvu.decode.FileURI(djvu_file_name))
    text = djvu.decode.PageText(document.pages[page_no], details=djvu.decode.TEXT_DETAILS_WORD)
    text.wait()
    export(text.sexpr, sys.stdout)

def do_import(djvu_file_name, page_no):
    context = djvu.decode.Context()
    document = context.new_document(djvu.decode.FileURI(djvu_file_name))
    text = djvu.decode.PageText(document.pages[page_no], details=djvu.decode.TEXT_DETAILS_WORD)
    text.wait()
    print(import_(text.sexpr, sys.stdin))

def main():
    ap = argparse.ArgumentParser()
    ap.add_argument('-p', '--page', dest='page_no', metavar='N', action='store', type=int, required=True)
    ag = ap.add_mutually_exclusive_group(required=True)
    ag.add_argument('-x', '--export', dest='action', action='store_const', const=do_export)
    ag.add_argument('-i', '--import', dest='action', action='store_const', const=do_import)
    ap.add_argument('file', metavar='FILE')
    options = ap.parse_args()
    options.action(options.file, options.page_no - 1)

if __name__ == '__main__':
    main()

# vim:ts=4 sts=4 sw=4 et
