#!/usr/bin/env python
# coding: utf-8

import argparse
import logging
import os
import sys
import json

from select_env_resource import get_shard_info, get_variable_from_env as select_env


def write_config(config_data, config_path):
    config_path = os.getcwd() + '/' + config_path.rstrip('.').split('description')[0] + '/description'
    with open(config_path, 'w') as config:
        config.write(json.dumps(config_data))
    logging.info('Config was writed to %s', config_path)


def get_env_wrapper(func, variable, **args):
    result = None
    try:
        result = func(variable, **args)
    except EnvironmentError:
        logging.exception('One of more environment variables was not found')
    return result


def render_description():
    description = {
        'ctype': get_env_wrapper(select_env, 'CUSTOM_CTYPE') or get_env_wrapper(select_env, 'LABELS_saas_ctype'),
        'servicetype': get_env_wrapper(select_env, 'INSTANCE_TAG_ITYPE'),
        'service': get_env_wrapper(select_env, 'LABELS_saas_service'),
        'shardmin': get_env_wrapper(get_shard_info, 'shard_min', display=False),
        'shardmax': get_env_wrapper(get_shard_info, 'shard_max', display=False),
        'slot': get_env_wrapper(select_env, 'HOSTNAME') + ':' + str(get_env_wrapper(select_env, 'BSCONFIG_IPORT')),
    }
    description['shard'] = description['shardmin'] + '-' + description['shardmax']
    logging.info('Generating config: %s', str(description))
    return description


def parse_args(args):
    opts = argparse.ArgumentParser(prog='render_description',
                                   formatter_class=argparse.RawTextHelpFormatter,
                                   description="""
DESCRIPTION
Tool for render description file using environment information

Example:
render_description.py -c ./config
""")

    opts.add_argument('-c', '--config', dest='config_path', type=str,
                      help='Specifies config path', default='configs')
    opts.add_argument('-d', '--dry', dest='dry_run', action='store_true',
                      help='Just render config and print', default=False)

    if args:
        opts = opts.parse_args(args)
    else:
        opts = opts.parse_args()
    return opts


if __name__ == '__main__':
    options = parse_args(sys.argv[1:])
    if not options.dry_run:
        write_config(render_description(), options.config_path)
    else:
        print(render_description())

