import logging
from logging.config import dictConfig
import argparse
import traceback
from shutil import rmtree
from os import mkdir
import os.path
from helper import *
from config import *
from swagger import Swagger
from schema import Schema, ResourceAttr

logging_config = dict(
    version=1,
    formatters={
        'f': {'format':
              '%(asctime)s %(name)-12s %(levelname)-8s %(message)s'}
        },
    handlers={
        'h': {'class': 'logging.FileHandler',
              'formatter': 'f',
              'filename': 'debug.log',
              'mode': 'w',
              'level': logging.DEBUG}
        },
    root={
        'handlers': ['h'],
        'level': logging.DEBUG,
        }
)

#
#   main of script
#

if __name__ == '__main__' and __package__ is None:
    from os import sys, path
    sys.path.append(path.dirname(path.dirname(path.abspath(__file__))))

    dictConfig(logging_config)
    logger = logging.getLogger(__name__)

    # version information
    my_version = "0.1"

    print("************************")
    print("swagger2x ", my_version)
    print("************************")
    parser = argparse.ArgumentParser()

    parser.add_argument("-schema_dir", "--schema_dir", default=None,
                        help="Schema directory", nargs='?', const="", required=True)
    parser.add_argument("-template_dir", "--template_dir", default=None,
                        help="Jinja Template dir", nargs='?', const="", required=True)
    parser.add_argument("-out_dir", "--out_dir", default=".",
                         help="output dir",  nargs='?', const="", required=True)

    args = parser.parse_args()
    swagger_config['schema_dir'] = args.schema_dir
    swagger_config['template_dir'] = args.template_dir
    swagger_config['out_dir'] = args.out_dir

    print("Schema Dir   : " + str(args.schema_dir))
    print("Template Dir : " + str(args.template_dir))
    print("Out Dir      : " + str(args.out_dir))
    print("")

    try:
        if os.path.exists(args.out_dir):
            rmtree(args.out_dir)
            mkdir(args.out_dir)
        else:
            mkdir(args.out_dir)

        logger.debug("Processing Swaggers")
        swagger = Swagger()
        swagger.process()

        logger.debug("Processing Schemas")
        res_attr = ResourceAttr(args.template_dir, args.out_dir)
        schema = Schema(res_attr)
        schema.process()

        logger.debug("Creating Resource Attributes Strings")
        res_attr.process()

    except Exception as e:
        logger.error("Error %s", e)
        traceback.print_exc()
        pass
