#!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys
import os
import fnmatch
import subprocess
import logging
import colorama
import coloredlogs
import pysam
import re

GENE_ID_REG = re.compile('gene_id "(.*?)"')
TRANSCRIPT_ID_REG = re.compile('transcript_id "(.*?)"')
EXON_NUMBER_REG = re.compile('exon_number "(.*?)"')
SAMPLE_REG = re.compile('(.*)\.\d+\.\d+')
GTFEXT = '.gtf.gz'


# coloraman init
colorama.init()
logger = logging.getLogger(__name__)
logger.setLevel('INFO')
coloredlogs.install(fmt='%(msg)s', level='INFO', logger=logger)

version = "0.7.1"

logo="""
                                                                       _____
`````|````|```````,    .'.     |..          |           ..'''|```````.~     ~.
     |    |''|''''   .''```.   |  ``..      |        .''     |''''''|         |
     |    |   `.   .'       `. |      ``..  |     ..'        |      |         |
     |    |     `.'           `|          ``....''           |       `._____.'
"""

def call_w_check(cmd, shell=True):
    """Redefine the subprocess.call to throw error when return != 0"""
    r = subprocess.call(cmd, shell=True)
    if r != 0:
        logger.error("Error when running command {}".format(cmd))
        sys.exit(1)


def myglob(path):
    directory, pattern = os.path.split(path)
    matches = []
    for root, dirnames, filenames in os.walk(directory):
        for filename in fnmatch.filter(filenames, pattern):
            matches.append(os.path.join(root, filename))
    return matches


def check_bam_header(bamfile):
    """Make sure bam mapped with HISAT"""
    with pysam.AlignmentFile(bamfile) as bam:
        header = bam.header
        if header['PG'][0]['ID'] != 'hisat2':
            logger.warning(('\n' + 3*'/!\\' + " Could not confirm {} mapped "
                            "with HISAT2 from header ".format(bamfile)) +
                           3*'/!\\' + '\n')


def cmd_exists(cmd):
    """Check if a command is in the path"""
    found = False
    for path in os.environ["PATH"].split(os.pathsep):
        if os.access(os.path.join(path, cmd), os.X_OK):
            found = True
            continue
    if not found:
        logger.error("{} not installed or not found in the path!".format(cmd))
        sys.exit(1)



def get_first(x):
    return x.iloc[0]


def join_pipe(x):
    return "|".join(set([str(i) for i in x if i != '.']))
