#!/usr/bin/env python

"""
Examples of usage:

Input data will be read from the specified file and the result will be
written to the specified file using custom elements mapping:

    $ html2bbcode --map map.conf input.html output.bbcode

Input data will be read from the specified file and the result will be
written to the standart output:

    $ html2bbcode input.html

Input data will be read from the standard input and the result will be
written to the specified file:

    $ cat input.html | html2bbcode output.bbcode

Input data will be read from the standard input and the result will be
written to the standard output:

    $ cat input.html | html2bbcode

"""
import argparse
import sys
from html2bbcode.parser import HTML2BBCode

if __name__ == '__main__':
    parser = argparse.ArgumentParser(
        description='HTML to BBCode converter',
        formatter_class=argparse.RawTextHelpFormatter,
        epilog=__doc__)
    parser.add_argument('file1', default=None, help='Input file', nargs='?')
    parser.add_argument('file2', default=None, help='Output file', nargs='?')
    parser.add_argument('--map', default=None, help='Mapping file elements')
    args = parser.parse_args()

    if sys.stdin.isatty():
        if not args.file1:
            parser.print_help()
            exit()
        input = open(args.file1, 'r').read()
        file2 = args.file2
    else:
        input = sys.stdin.read()
        file2 = args.file1

    output = HTML2BBCode(map=args.map).feed(input)
    if file2:
        with open(file2, 'w') as f:
            f.write(output)
    else:
        sys.stdout.write(output)
