#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Convert unicode to the closest ascii equivalent.
#
# See README.md for more information.
#
# See LICENSE for licensing information.
#

from __future__ import print_function

import argparse
import logging
import re
import sys

from uni2ascii import uni2ascii

VERSION = '1.0.0'


class Global:
    """Stores globals. There should be no instances of Global."""

    # Command line arguments. Set by parse_arguments().
    args = None
# end class Global


def main(argv):
    parse_arguments(argv[1:])
    setup_logging()

    for line in sys.stdin:
        line = uni2ascii(line)

        # If there's remaining non-ascii, handle it according to arguments.
        # The default is to leave the line alone.

        if re.search(r'[^\x00-\x7f]', line):
            if Global.args.e:
                logging.error('Unexpected non-ascii. The line was:\n%s\n', line)
                sys.exit(1)
            if Global.args.X:
                continue
            if Global.args.r or Global.args.x:
                if Global.args.x:
                    replace = ''
                else:
                    replace = Global.args.r
                line = re.sub(r'[^\x00-\x7f]+', replace, line).strip()
        # If we get here, we should print a line
        print(line)
# end main()


def parse_arguments(strs):
    parser = argparse.ArgumentParser(
        description="Replace unicode characters that look similar to ASCII with their nearest ASCII equivalent. Version {VERSION}.".format(VERSION=VERSION))
    parser.add_argument('-loglevel',
                        choices=['DEBUG', 'INFO', 'WARNING', 'ERROR', 'CRITICAL'],
                        default='WARNING',
                        help='Logging level (default %(default)s).')
    parser.add_argument('-version', '--version', action='version', version=str(VERSION))
    mogroup = parser.add_mutually_exclusive_group()
    mogroup.add_argument(
        '-r',
        help='Replace remaining non-ascii characters with this string.')
    mogroup.add_argument(
        '-x',
        help='Remove remaining non-ascii characters.', action='store_true')
    mogroup.add_argument(
        '-X',
        action='store_true',
        help='Silently remove lines containing any remaining non-ascii characters.')
    mogroup.add_argument(
        '-e',
        action='store_true',
        help='Report an error and exit if there are any remaining non-ascii characters.')
    Global.args = parser.parse_args(strs)
# end parse_arguments()


def setup_logging():
    numeric_level = getattr(logging, Global.args.loglevel, None)
    if not isinstance(numeric_level, int):
        raise ValueError('Invalid log level: {loglevel}'.format(loglevel=Global.args.loglevel))
    logging.basicConfig(level=numeric_level,
                        format="%(module)s:%(levelname)s:%(asctime)s: %(message)s",
                        datefmt='%Y-%m-%d %H:%M:%S')
# end setup_logging()


if __name__ == "__main__":
    main(sys.argv)
