# -*- coding: utf-8 -*-
import os
import shutil
import sys
import logging

import __res

ENCODING = 'utf-8'


def load_resources(prefix):
    for key, value in __res.iter_keys(prefix.encode(ENCODING)):
        print("Loading {} at {}".format(key, key[len(prefix) + 1:]))
        yield key[len(prefix) + 1:], __res.find(key)


def load_and_write_resources(prefix):
    """
    This method loads all resources from __res and write it as files.
    Works only for Arcadia building.
    """
    try:
        output_folder = prefix.lstrip('/')
        if os.path.isdir(output_folder):
            shutil.rmtree(output_folder)
        for resource_path_suffix, resource_data in load_resources(prefix):
            resource_path = os.path.join(output_folder, resource_path_suffix.decode())
            resource_dir = os.path.dirname(resource_path)
            if not os.path.isdir(resource_dir):
                os.makedirs(resource_dir)
            with open(resource_path, 'wb') as f:
                f.write(resource_data)
    except ImportError as e:
        raise Exception('Cannot import resources: {}'.format(e))


def get_ferryman_name(service_name, service_ctype='', old_names_format=False):
    """
    Method for compare name of ferryman nanny service
    :param service_name: type str
    :param service_ctype: type str
    :param old_names_format: type bool
    :return:
    """
    if old_names_format:
        prefix = 'saas_ferryman_'
        service = service_name.replace('-', '_')
    else:
        prefix = 'saas_fm_'
        service = service_name

    ferryman_name = prefix + service
    if 'prestable' in service_ctype:
        ferryman_name += '_p'
    if 'hamster' in service_ctype:
        ferryman_name += '_h'
    return ferryman_name


def collect_users_from_string(logins):
    """
    Method for collecting logins from string different separated
    :param logins: type str
    :return: type list
    """
    if ',' in logins:
        users_list = [user.strip().strip('@') for user in logins.split(',')]
    elif ';' in logins:
        users_list = [user.strip().strip('@') for user in logins.split(';')]
    else:
        users_list = [user.strip().strip('@') for user in logins.split()]
    return users_list


def prepare_logging(options):
    """
    Prepare logging settings
    :param options: argparse.Namespace
    """
    basedir = os.getcwd()
    logdir = '%s/logs' % basedir
    if not os.path.exists(logdir):
        os.makedirs(logdir)

    if options.debug:
        level = logging.DEBUG
    else:
        level = logging.INFO

    logging.basicConfig(
        level=level,
        format='%(asctime)s | %(filename)18s#%(lineno)s | %(levelname)-5s | %(message)s',
        datefmt='%H:%M:%S',
        filename='logs/{}'.format(sys.argv[0].split('/')[-1]))

    console = logging.StreamHandler()
    console.addFilter(logging.Filter(name='root'))
    console.setFormatter(logging.Formatter('[%(module)18s][%(levelname)-5s] %(message)-20s '))
    console.setLevel(level)
    logging.getLogger('').addHandler(console)
