# Path: snakemakelib/log.py
# class LoggerManager(object):
#     __metaclass__ = Singleton
# 
#     _loggers = {}
#     _fmt = "%(asctime)s (%(levelname)s) %(name)s :  %(message)s"
#     _ch = logging.StreamHandler()
#     _formatter = logging.Formatter(_fmt)
#     _ch.setFormatter(_formatter)
#     _has_loaded_config = False
# 
#     def __init__(self, *args, **kwargs):
#         if not LoggerManager._has_loaded_config:
#             # Add snakemakelib root handler
#             LoggerManager._loggers['snakemakelib'] = logging.getLogger('snakemakelib')
#             LoggerManager._loggers['snakemakelib'].setLevel(logging.WARNING)
#             LoggerManager._loggers['snakemakelib'].addHandler(LoggerManager._ch)
#             self._load_config()
#             LoggerManager._has_loaded_config = True
# 
#     def _load_config(self):
#         conf = {}
#         if os.path.exists("logconf.yaml"):
#             with open ("logconf.yaml", "r") as fh:
#                 conf = yaml.load(fh)
#         else:
#             conf = self._load_sml_config()
#         if conf:
#             logging.config.dictConfig(conf)
#      
#     def _load_sml_config(self):
#         cfg = {}
#         for fn in [os.path.join(os.getenv("HOME"), ".smlconf.yaml"),
#                    os.path.join(os.curdir, "smlconf.yaml")]:
#             if (fn is None):
#                 continue
#             if not os.path.exists(fn):
#                 continue
#             with open(fn, "r") as fh:
#                 cfg_tmp = yaml.load(fh)
#             if cfg_tmp:
#                 cfg.update(cfg_tmp)
#         return cfg.get("logging", {})
# 
#     @staticmethod
#     def getLogger(name=None):
#         if not name:
#             smllogger = logging.getLogger()
#             return logging.getLogger()
#         elif name not in LoggerManager._loggers.keys():
#             LoggerManager._loggers[name] = logging.getLogger(str(name))
#             LoggerManager._loggers[name].addHandler(LoggerManager._ch)
#             return LoggerManager._loggers[name]
#         else:
#             logging.warn("Trying to get already existing logger")


import os
import csv
    import sys
from snakemake.utils import update_config
from snakemakelib.log import LoggerManager
    Args: 
      metadata - file name
      config - configuration to update
    """
    metadata_list = []
    if metadata_file in sys.argv:
        return config
    try:
        with open(metadata_file, "r") as fh:
            reader = csv.DictReader(fh.readlines())
        metadata_list = [row for row in reader]
        run2sample = {row["Run"]:row["SampleName"] for row in metadata_list}
        config_default = {
            'bio.ngs.settings' : {
                'sampleinfo' : metadata_file
            },
            'bio.ngs.tools.sratools': {
                '_datadir': os.path.dirname(metadata_file),
                '_run2sample' : run2sample,
                '_metadata' : metadata_list
            },
        }
        update_config(config_default, config)
        config = config_default
        
    except Exception:
        raise Exception("""

        no metadata file '{metadata}' found


# Path: snakemakelib/log.py
# class LoggerManager(object):
#     __metaclass__ = Singleton
# 
#     _loggers = {}
#     _fmt = "%(asctime)s (%(levelname)s) %(name)s :  %(message)s"
#     _ch = logging.StreamHandler()
#     _formatter = logging.Formatter(_fmt)
#     _ch.setFormatter(_formatter)
#     _has_loaded_config = False
# 
#     def __init__(self, *args, **kwargs):
#         if not LoggerManager._has_loaded_config:
#             # Add snakemakelib root handler
#             LoggerManager._loggers['snakemakelib'] = logging.getLogger('snakemakelib')
#             LoggerManager._loggers['snakemakelib'].setLevel(logging.WARNING)
#             LoggerManager._loggers['snakemakelib'].addHandler(LoggerManager._ch)
#             self._load_config()
#             LoggerManager._has_loaded_config = True
# 
#     def _load_config(self):
#         conf = {}
#         if os.path.exists("logconf.yaml"):
#             with open ("logconf.yaml", "r") as fh:
#                 conf = yaml.load(fh)
#         else:
#             conf = self._load_sml_config()
#         if conf:
#             logging.config.dictConfig(conf)
#      
#     def _load_sml_config(self):
#         cfg = {}
#         for fn in [os.path.join(os.getenv("HOME"), ".smlconf.yaml"),
#                    os.path.join(os.curdir, "smlconf.yaml")]:
#             if (fn is None):
#                 continue
#             if not os.path.exists(fn):
#                 continue
#             with open(fn, "r") as fh:
#                 cfg_tmp = yaml.load(fh)
#             if cfg_tmp:
#                 cfg.update(cfg_tmp)
#         return cfg.get("logging", {})
# 
#     @staticmethod
#     def getLogger(name=None):
#         if not name:
#             smllogger = logging.getLogger()
#             return logging.getLogger()
#         elif name not in LoggerManager._loggers.keys():
#             LoggerManager._loggers[name] = logging.getLogger(str(name))
#             LoggerManager._loggers[name].addHandler(LoggerManager._ch)
#             return LoggerManager._loggers[name]
#         else:
#             logging.warn("Trying to get already existing logger")


# Path: snakemakelib/bio/ngs/tools/sratools.py
import os
import csv
    import sys
from snakemake.utils import update_config
from snakemakelib.log import LoggerManager

    Args: 
      metadata - file name
      config - configuration to update
    """
    metadata_list = []
    if metadata_file in sys.argv:
        return config
    try:
        with open(metadata_file, "r") as fh:
            reader = csv.DictReader(fh.readlines())
        metadata_list = [row for row in reader]
        run2sample = {row["Run"]:row["SampleName"] for row in metadata_list}
        config_default = {
            'bio.ngs.settings' : {
                'sampleinfo' : metadata_file
            },
            'bio.ngs.tools.sratools': {
                '_datadir': os.path.dirname(metadata_file),
                '_run2sample' : run2sample,
                '_metadata' : metadata_list
            },
        }
        update_config(config_default, config)
        config = config_default
        
    except Exception:
        raise Exception("""

        no metadata file '{metadata}' found


        please initiate analysis by running 'snakemake {metadata}'