import logging
from logging.config import dictConfig
import argparse
import traceback
from shutil import rmtree
from os import mkdir
from package.helper import *
from package.config import *
from package.swagger import Swagger
from package.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__':
    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("-template_dir", "--template_dir",
                        help="Jinja Template dir", required=True)
    parser.add_argument("-out_dir", "--out_dir",
                         help="output dir", required=True)
    parser.add_argument("-schema_dir", "--schema_dir",
                        help="Schema directory", action='append', 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))

    try:
        if os.path.exists(args.out_dir):
            rmtree(args.out_dir)
        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
