#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
from __future__ import print_function, unicode_literals

import argparse
import sys

# pylint: disable=import-self
import betterbib
from betterbib import pybtex_to_bibtex_string
from pybtex.database.input import bibtex


def _main():
    args = _parse_cmd_arguments()

    updater = betterbib.JournalNameUpdater(args.long_journal_names)

    data = bibtex.Parser().parse_file(args.infile)
    for key in data.entries:
        updater.update(data.entries[key])

    _write(data.entries, args.outfile, 'curly')
    return


def _write(od, out, delimeter_type):
    # Write header to the output file.
    out.write(
        '%%comment{This file was created with betterbib v%s.}\n\n' %
        betterbib.__version__
        )

    # Create the dictionary only once
    dictionary = betterbib.create_dict()

    # write the data out sequentially to respect ordering
    for bib_id, d in od.items():
        brace_delimeters = delimeter_type == 'curly'
        a = pybtex_to_bibtex_string(
            d, bib_id, brace_delimeters=brace_delimeters,
            dictionary=dictionary
            )
        out.write(a + '\n\n')
    return


def _parse_cmd_arguments():
    parser = argparse.ArgumentParser(
        description='(Un)abbreviate journal names.'
        )
    parser.add_argument(
        '-v', '--version',
        help='display version information',
        action='version',
        version='betterbib {}, Python {}'.format(
            betterbib.__version__, sys.version
            )
        )
    parser.add_argument(
        'infile',
        nargs='?',
        type=argparse.FileType('r'),
        default=sys.stdin,
        help='input BibTeX file (default: stdin)'
        )
    parser.add_argument(
        'outfile',
        nargs='?',
        type=argparse.FileType('w'),
        default=sys.stdout,
        help='output BibTeX file (default: stdout)'
        )
    parser.add_argument(
        '-l', '--long-journal-names',
        action='store_true',
        help='use long journal names (default: false)'
        )
    return parser.parse_args()


if __name__ == '__main__':
    _main()
