# Path: snakemakelib/utils.py
# def isoformat(s=None):
#     """Return isoformat date from string"""
#     if s is None:
#         return
#     # Assume YYMMDD format
#     if len(s) == 6:
#         (YY, MM, DD) = (s[0:2], s[2:4], s[4:6])
#         return date(int("20{YY}".format(YY=YY)), int(MM.lstrip("0")), int(DD)).isoformat()
# 
# 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 re
import os
from itertools import groupby
from snakemakelib.utils import isoformat
from snakemakelib.log import LoggerManager
# PM Platform model. Free-form text providing further details of the platform/technology used.

# PU Platform unit (e.g. flowcell-barcode.lane for Illumina or slide for SOLiD). Unique identifier.

# SM Sample. Use pool name where a pool is being sequenced.


class ReadGroup(RunRegexp):
    """Adds formatting function for generating read group option string"""
    _group_keys = ['ID', 'CN', 'DS', 'DT', 'FO', 'KS',
                   'LB', 'PG', 'PI', 'PL', 'PU', 'SM']
    _extra_keys = ['PATH']
    _group_dict = {'ID': 'identifier', 'CN': 'center', 'DS': 'description',
                   'DT': 'date', 'FO': 'floworder', 'KS': 'keysequence',
                   'LB': 'library', 'PG': 'program', 'PI': 'insertsize',
                   'PL': 'platform', 'PU': 'platform-unit', 'SM': 'sample'}

    def __init__(self, regexp=None, opt_prefix="--", *args, **kwargs):
        super(ReadGroup, self).__init__(regexp, *args, **kwargs)
        self._opt_prefix = opt_prefix

    def _post_process_keys(self, m):
        self['PATH'] = os.path.dirname(m.string)
        if 'ID' not in self.keys() or not self.get('ID', ""):
            # inv_map = {v: k for (k, v) in list(self.re.groupindex.items())}
            self['ID'] = os.path.basename(self.fmt.format(**self))

    def _fmt_string(self, k):
        """Take care of date string"""
        if k == 'DT':

# Path: snakemakelib/utils.py
# def isoformat(s=None):
#     """Return isoformat date from string"""
#     if s is None:
#         return
#     # Assume YYMMDD format
#     if len(s) == 6:
#         (YY, MM, DD) = (s[0:2], s[2:4], s[4:6])
#         return date(int("20{YY}".format(YY=YY)), int(MM.lstrip("0")), int(DD)).isoformat()
# 
# 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/regexp.py
import re
import os
from itertools import groupby
from snakemakelib.utils import isoformat
from snakemakelib.log import LoggerManager

# PM Platform model. Free-form text providing further details of the platform/technology used.

# PU Platform unit (e.g. flowcell-barcode.lane for Illumina or slide for SOLiD). Unique identifier.

# SM Sample. Use pool name where a pool is being sequenced.


class ReadGroup(RunRegexp):
    """Adds formatting function for generating read group option string"""
    _group_keys = ['ID', 'CN', 'DS', 'DT', 'FO', 'KS',
                   'LB', 'PG', 'PI', 'PL', 'PU', 'SM']
    _extra_keys = ['PATH']
    _group_dict = {'ID': 'identifier', 'CN': 'center', 'DS': 'description',
                   'DT': 'date', 'FO': 'floworder', 'KS': 'keysequence',
                   'LB': 'library', 'PG': 'program', 'PI': 'insertsize',
                   'PL': 'platform', 'PU': 'platform-unit', 'SM': 'sample'}

    def __init__(self, regexp=None, opt_prefix="--", *args, **kwargs):
        super(ReadGroup, self).__init__(regexp, *args, **kwargs)
        self._opt_prefix = opt_prefix

    def _post_process_keys(self, m):
        self['PATH'] = os.path.dirname(m.string)
        if 'ID' not in self.keys() or not self.get('ID', ""):
            # inv_map = {v: k for (k, v) in list(self.re.groupindex.items())}
            self['ID'] = os.path.basename(self.fmt.format(**self))

    def _fmt_string(self, k):
        """Take care of date string"""
        if k == 'DT':

            return isoformat(self[k])