from airflow import DAG
from airflow.operators import BashOperator, PythonOperator
from datetime import datetime, timedelta

import os
import logging
from subprocess import call

import tracker.model
from tracker.model.analysis_run import *

CONTIG_NAMES = ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10",
                "11", "12", "13", "14", "15", "16", "17", "18", "19", 
                "20", "21", "22", "X", "Y"]


logger = logging.getLogger()


def get_config(kwargs):
    return kwargs["dag_run"].conf["config"]


def get_sample(kwargs):
    return kwargs["dag_run"].conf["config"]["sample"]


def start_analysis_run(**kwargs):

    config = get_config(kwargs)

    analysis_run_id = config["analysis_run_id"]

    analysis_run = get_analysis_run_by_id(analysis_run_id)
    set_in_progress(analysis_run)


def complete_analysis_run(**kwargs):

    config = get_config(kwargs)
    analysis_run_id = config["analysis_run_id"]

    analysis_run = get_analysis_run_by_id(analysis_run_id)

    set_completed(analysis_run)


def set_error_analysis_run(**kwargs):

    config = get_config(kwargs)
    analysis_run_id = config["analysis_run_id"]

    analysis_run = get_analysis_run_by_id(analysis_run_id)

    set_error(analysis_run)


def validate_sample(**kwargs):
    my_sample = get_sample(kwargs)

    sample_location = my_sample["sample_location"]

    logger.info("Trying to locate sample at %s", sample_location)

    if not os.path.isfile(sample_location):
        raise ValueError(
            "Invalid sample location or wrong permissions at {}".format(sample_location))


def call_command(command, command_name, cwd=None):
    logger.info(
        "About to invoke {} with command {}.".format(command_name, command))

    try:
        retcode = call(command, shell=True, cwd=cwd)
        if retcode != 0:
            msg = "{} terminated by signal {}.".format(command_name, retcode)
            logger.error(msg)
            raise Exception(msg)
        else:
            logger.info("{} terminated normally.".format(command_name))
    except OSError as e:
        logger.error("{} execution failed {}.".format(command_name, e))
        raise


def compress_sample(result_filename, config):
    compressed_filename = result_filename + ".gz"

    bgzip = config["bgzip"]
    compression_command = "{} {} {}".format(
        bgzip["path"], bgzip["flags"], result_filename)

    call_command(compression_command, "compression")

    return compressed_filename

def uncompress_gzip_sample(result_filename, config):
    new_result_filename = os.path.splitext(result_filename)[0]
    uncompress_command = "gzip -d {}".format(result_filename)
    call_command(uncompress_command, "gzip")
    
    return new_result_filename


def generate_tabix(compressed_filename, config):

    tabix = config["tabix"]

    tabix_command = "{} {} {}".format(
        tabix["path"], tabix["flags"], compressed_filename)

    call_command(tabix_command, "tabix")


def copy_result(result_file_name, sample_id, config):

    results_location = "{}/{}".format(config["results_base_path"], sample_id)
    results_directory_command = "mkdir -p {}".format(results_location)

    call_command(results_directory_command, "mkdir")

    rsync = config["rsync"]
    rsync_command = "rsync {} {}* {}".format(
        rsync["flags"], result_file_name, results_location)

    call_command(rsync_command, "rsync")

@@ -170,16 +170,59 @@
 ort call
+, check_output, STDOUT, CalledProcessError%0A
 %0A%0Aimport
@@ -414,17 +414,16 @@
 %22, %2219%22,
- 
 %0A       
@@ -1769,17 +1769,17 @@
 ommand))
-%0A
+ 
 %0A    try
@@ -1792,22 +1792,29 @@
     
-retcode = call
+output = check_output
 (com
@@ -1842,187 +1842,86 @@
 =cwd
-)%0A        if retcode != 0:%0A            msg = %22%7B%7D terminated by signal %7B%7D.%22.format(command_name, retcode)%0A            logger.error(msg)%0A            raise Exception(msg)%0A        els
+, stderr=STDOUT)%0A        logger.info(output)%0A    except CalledProcessError as 
 e:%0A 
@@ -1931,96 +1931,30 @@
     
- 
-   
 logger.
-info(%22%7B%7D terminated normally.%22.format(command_name))%0A    except OSError as e:
+error(e.output)
 %0A   
@@ -2019,16 +2019,27 @@
 _name, e
+.returncode
 ))%0A     
@@ -2362,16 +2362,17 @@
 lename%0A%0A
+%0A
 def unco
@@ -2586,20 +2586,16 @@
 %22gzip%22)%0A
-    
 %0A    ret

Change to calling check_output instead of call when invoking external programs in order to get stdout and stderr into the log.