#!/usr/bin/env python
# bax_to_bam 0.0.1
# Generated by dx-app-wizard.
#
# Basic execution pattern: Your app will run on a single machine from
# beginning to end.
#
# See https://wiki.dnanexus.com/Developer-Portal for documentation and
# tutorials on how to modify this file.
#
# DNAnexus Python Bindings (dxpy) documentation:
#   http://autodoc.dnanexus.com/bindings/python/current/

import os
import subprocess

import dxpy


os.environ['PATH'] = '/longranger-2.2.2' + os.pathsep + os.environ['PATH']


def run_cmd(cmd, returnOutput=False):
    print cmd
    if returnOutput:
        output = subprocess.check_output(cmd, shell=True, executable='/bin/bash').strip()
        print output
        return output
    else:
        subprocess.check_call(cmd, shell=True, executable='/bin/bash')


def remove_special_chars(string):
    '''function that replaces any characters in a string that are not alphanumeric or _ or .'''
    string = "".join(
        char for char in string if char.isalnum() or char in ['_', '.'])

    return string


def untar_to_work_dir(targz_link, target_dir, added_args=''):
    input_file = dxpy.DXFile(targz_link)
    input_filename = input_file.describe()['name']

    cmd = 'dx download ' + input_file.get_id() + ' -o - '
    if input_filename.endswith('.tar.gz'):
        cmd += '| tar -xzvf - -C {0} '.format(target_dir)
    elif input_filename.endswith('.tar'):
        cmd += '| tar -xvf - -C {0} '.format(target_dir)

    cmd += added_args
    run_cmd(cmd)


def download_and_gunzip_file(input_file, skip_decompress=False, additional_pipe=None):
    input_file = dxpy.DXFile(input_file)
    input_filename = input_file.describe()['name']
    ofn = remove_special_chars(input_filename)

    cmd = 'dx download ' + input_file.get_id() + ' -o - '
    if input_filename.endswith('.tar.gz'):
        ofn = 'tar_output_{0}'.format(ofn.replace('.tar.gz', ''))
        cmd += '| tar -zxvf - '
    elif (os.path.splitext(input_filename)[-1] == '.gz') and not skip_decompress:
        cmd += '| gunzip '
        ofn = os.path.splitext(ofn)[0]
    if additional_pipe is not None:
        cmd += '| ' + additional_pipe
    cmd += ' > ' + ofn
    print cmd
    subprocess.check_call(cmd, shell=True)

    return ofn


@dxpy.entry_point('main')
def main(**job_inputs):
    ref_fasta_file = download_and_gunzip_file(job_inputs['ref_fasta'])

    longranger_cmd = 'longranger mkref {0} '.format(ref_fasta_file)
    run_cmd(longranger_cmd)

    output_prefix = '.'.join(ref_fasta_file.split('.')[:-1])
    expected_output = 'refdata-{0}'.format(output_prefix)

    run_cmd('tree {0}'.format(expected_output))

    if 'sv_blacklist_file' in job_inputs:
        sv_blacklist_file = download_and_gunzip_file(job_inputs['sv_blacklist_file'])
        cmd = 'mv {0} {1}'.format(
            sv_blacklist_file, os.path.join(expected_output, 'regions/sv_blacklist.bed'))
        run_cmd(cmd)

    if 'segdup_file' in job_inputs:
        segdup_file = download_and_gunzip_file(job_inputs['segdup_file'])
        cmd = 'mv {0} {1}'.format(
            segdup_file, os.path.join(expected_output, '/regions/segdups.bedpe'))
        run_cmd(cmd)

    if 'gene_annotation' in job_inputs:
        gene_annotation = download_and_gunzip_file(
            job_inputs['gene_annotation'], skip_decompress=True)
        if not gene_annotation.endswith('.gz'):
            cmd = 'gzip {0}'.format(gene_annotation)
            run_cmd(cmd)
            gene_annotation = gene_annotation + '.gz'

        cmd = 'mv {0} {1}'.format(
            gene_annotation, os.path.join(expected_output, '/genes/gene_annotations.gtf.gz'))
        run_cmd(cmd)

    if 'primary_contigs' in job_inputs:
        primary_contigs = download_and_gunzip_file(job_inputs['primary_contigs'])

        cmd = 'mv {0} {1}'.format(
            primary_contigs, os.path.join(expected_output, '/fasta/primary_contigs.txt'))
        run_cmd(cmd)

    if 'sex_chrom_file' in job_inputs:
        sex_chrom_file = download_and_gunzip_file(job_inputs['sex_chrom_file'])

        cmd = 'mv {0} {1}'.format(
            sex_chrom_file, os.path.join(expected_output, '/fasta/sex_chromosomes.tsv'))
        run_cmd(cmd)

    # package up the ref directory
    output_tar = output_prefix + '.tar.gz'
    cmd = 'tar -czvf {tar} {path} '.format(tar=output_tar, path=expected_output)
    run_cmd(cmd)

    output = {'ref_targz': dxpy.dxlink(dxpy.upload_local_file(output_tar))}
    return output

dxpy.run()
