#!python
import sys
import logging
import os
import argparse

from bib2glossary.utils import ErrorParser, cmndline_prompt
from bib2glossary.acronyms import bib_to_tex

logger = logging.getLogger('bib2glossary.bib2acronym')


def run(fpath, outpath, abbrev_field, full_field):

    root = logging.getLogger()
    root.handlers = []  # remove any existing handlers
    root.setLevel(logging.DEBUG)
    stream_handler = logging.StreamHandler(sys.stdout)
    stream_handler.setLevel(logging.INFO)
    formatter = logging.Formatter('%(levelname)8s: %(module)10s: %(message)s')
    stream_handler.setFormatter(formatter)
    stream_handler.propogate = False
    root.addHandler(stream_handler)

    if not os.path.exists(fpath):
        logger.critical(IOError('input path does not exist: {}'.format(fpath)))
        return

    with open(fpath) as file_obj:
        out_str_list = bib_to_tex(file_obj.read(),
                                  abbrev_field=abbrev_field, full_field=full_field)

    if not out_str_list:
        logger.warn("No bib entries found")

    out_str_list.insert(0, "% Created by bib2glossary")

    with open(outpath, "w") as file_obj:
        file_obj.write("\n".join(out_str_list))

    logger.info("Successfully output to: {}".format(outpath))


if __name__ == "__main__":

    parser = ErrorParser(
        description='convert a bibtex file to a tex file '
        'containing acronym definitions',
        formatter_class=argparse.ArgumentDefaultsHelpFormatter
    )
    parser.add_argument("fpath", type=str,
                        help='bibtex file path', metavar='filepath')
    parser.add_argument("-a", "--abbrev-field", type=str, default='shorttitle',
                        metavar='field',
                        help='the bib field defining the abbreviation')
    parser.add_argument("-f", "--full-field", type=str, default='abstract',
                        metavar='field',
                        help='the bib field defining the full name')

    args = parser.parse_args()
    options = vars(args)

    fpath = os.path.abspath(options.pop('fpath'))
    outdir = os.getcwd()
    outname = os.path.splitext(os.path.basename(fpath))[0] + ".tex"
    outpath = os.path.join(outdir, outname)

    if os.path.exists(outpath):
        if not cmndline_prompt("Are sure you wish to overwrite the existing: {}?".format(outname)):
            sys.exit()

    run(fpath, outpath, options["abbrev_field"], options["full_field"])
