#!/usr/bin/env python
"""
Program that shows the program on the right and its abstract syntax tree (ast) on the left.
"""
from __future__ import print_function

import os
#os.environ.setdefault('QT_API', 'pyside')
#os.environ.setdefault('QT_API', 'pyqt5')

import sys, argparse, logging


from astviewer.qtpy import QtCore, QtWidgets

from astviewer.misc import logging_basic_config, handleException
from astviewer.misc import PROGRAM_NAME, PROGRAM_VERSION, PYTHON_VERSION, QT_API_NAME, QT_API
from astviewer.main import view

logger = logging.getLogger(__name__)

sys.excepthook = handleException

        
def main():
    """ Main program to test stand alone 
    """
    parser = argparse.ArgumentParser(description='Python abstract syntax tree viewer')
    parser.add_argument(dest='file_name', help='Python input file', nargs='?')
    parser.add_argument('-m', '--mode', dest='mode', default = 'exec',
        choices = ('exec', 'eval', 'single'),  
        help = """The mode argument specifies what kind of code must be compiled; 
            it can be 'exec' if source consists of a sequence of statements, 
            'eval' if it consists of a single expression, or 'single' if it 
            consists of a single interactive statement (in the latter case, 
            expression statements that evaluate to something other than None 
            will be printed). """)    
    parser.add_argument('-l', '--log-level', dest='log_level', default = 'warn', 
        choices = ('debug', 'info', 'warn', 'error', 'critical'),                      
        help = "Log level. Only log messages with a level higher or equal than this "
            "will be printed. Default: 'warn'")
    parser.add_argument('--reset', dest='reset', action="store_true",
        help = """If given, the persistent settings, such as window position and size,
                  will be reset to their default values.""")
    parser.add_argument('-v', '--version', action = 'store_true',
        help="Prints the program version.")

    args = parser.parse_args()

    logging_basic_config(args.log_level.upper())

    if args.version:
        print('{} {}'.format(PROGRAM_NAME, PROGRAM_VERSION))
        sys.exit(0)

    logger.info('Started {} {}'.format(PROGRAM_NAME, PROGRAM_VERSION))
    logger.info('Using Python {} and {} (api={})'.format(PYTHON_VERSION, QT_API_NAME, QT_API))

    try:
        QtWidgets.QApplication.setAttribute(QtCore.Qt.AA_UseHighDpiPixmaps)
    except Exception as ex:
        logger.debug("AA_UseHighDpiPixmaps not available in PyQt4: {}".format(ex))

    _app = QtWidgets.QApplication([])

    exit_code = view(file_name = args.file_name, mode = args.mode, reset = args.reset)
    logging.info('Done {}'.format(PROGRAM_NAME))
    sys.exit(exit_code)


if __name__ == '__main__':
    main()
