from __future__ import division
from falcon_kit.io import (
        log, syscall, capture,
)
import logging
import os
import re

LOG = logging.getLogger(__name__)

def parse_version(version):
    """
    >>> parse_version('1.222.33')
    ['1', '222', '33']
    >>> parse_version('1.222')
    ['1', '222']
    >>> parse_version('4.0.0beta')
    ['4', '0', '0beta']
    """
    return version.split('.')


def validate_samtools(samtools_output):
    """Given the result of a bare call to 'samtools',
    prove our $PATH is using at least version 1.3.0
    """
    try:
        re_output = re.compile(r'Version:\s+(?P<version>\S+)')
        mo = re_output.search(samtools_output)
        version = parse_version(mo.group('version'))
        major = int(version[0])
        minor = int(version[1])
    except Exception:
        msg = samtools_output + '\n---\nCould not discern version of samtools. We need at least 1.3.0. Good luck!'
        LOG.exception(msg)
        return
    if major < 1 or (major == 1 and minor < 3):
        msg = 'samtools is version {}, but we require >= 1.3.0'.format(
                version)
        raise Exception(msg)
    else:
        LOG.info('samtools {} is >= 1.3'.format(version))

def validate_nucmer(output):
    try:
        #re_output = re.compile(r'Version:\s+(?P<version>\S+)')
        #mo = re_output.search(output)
        #version = parse_version(mo.group('version'))
        version = parse_version(output.strip())
        major = int(version[0])
        minor = int(version[1])
    except Exception:
        msg = output + '\n---\nCould not discern version of nucmer. We need at least 4.0.0. Good luck!'
        LOG.exception(msg)
        return
    if major < 4:
        msg = 'nucmer is version {}, but we require >= 4.0.0'.format(
                version)
        raise Exception(msg)
    else:
        LOG.info('nucmer {} is >= 4.0.0'.format(version))

def validate_bwa(output):
    assert 'Usage: bwa mem' in output

def validate_config(config):
    # This simple and quick check catches common problems early.
    smrt_bin_cmds = [
        'samtools',
    ]
    path_cmds = [
        'nucmer',
        'show-coords',
        'delta-filter',
        'bwa',
        'bedtools',
    ]
    LOG.info('PATH={}'.format(os.environ['PATH']))
    try:
        syscall('which which')
    except Exception:
        LOG.warning('Could not find "which" command. Skipping checks for "blasr", etc.')
        return
    for cmd in smrt_bin_cmds + path_cmds:
        syscall('which ' + cmd)
    validate_nucmer(capture('nucmer --version'))
    validate_bwa(capture('bwa mem', nocheck=True))
    capture('show-coords -h')
    capture('delta-filter -h')
    syscall('bedtools --version')

    samtools_output = capture('samtools', nocheck=True)
    validate_samtools(samtools_output)
