import argparse
import subprocess

parser = argparse.ArgumentParser(description='Script to identify the intersecting variants between file1 and file2')

parser.add_argument('--outfile',help='Output file name',required=True)
parser.add_argument('--exome',help='BED file with coordinates of exonic targets',required=True)
parser.add_argument('--afs_table',help='Text file with AFs generated by process_AFs.py',required=True)
parser.add_argument('--label',help='Label used for column added to file1 when 2 variants intersect',required=True)
parser.add_argument('--bedtools_folder',help='Folder containing the bedtools binary',required=True)

args = parser.parse_args()


def get_overlapping_variants(file1,file2,label,bedtools_folder):
    '''
    Function to identify the intersecting variants between file1 and file2. This function makes use of Bedtools intersect

    Parameters
    ----------
    file1: filename
           Path to 1st file containing the variants to be intersected. A new column will be appended to this file depending on the intersection
           with the 2nd file
    file2: filename
           Path to 2nd file containing the variants to be intersected
    label: str
           Label used for the column added to file1 when 2 variants intersect
    bedtools_folder: str
                     Folder containing the BEDtools binary

    Returns
    -------
    filename
            File1 will be returned with a column added depending on the intersection with file1
    '''

    cmd="""awk '{ print $1\"\\t\"$2\"\\t\"$3 }' %s | %s/bedtools intersect -a - -b %s """ % (file1,bedtools_folder,file2)

    intersect_list=[]

    try:
        out = subprocess.check_output(cmd, shell=True,executable='/bin/bash').decode("utf-8").split("\n")
        for l in out:
            if len(l.split('\t'))==3: intersect_list.append(l.split('\t')[1])
    except subprocess.CalledProcessError as e:
        raise

    wf=open(args.outfile,'w')
    with open(file1) as f:
        for line in f:
            line=line.rstrip("\n")
            if line.startswith("#"):
                line=line+"\t{0}".format(label)
                wf.write(line+"\n")
                continue
            if line.split("\t")[1] in intersect_list:
                line= line+"\t1"
            else:
                line=line+"\t0"
            wf.write(line+"\n")
    wf.close()

get_overlapping_variants(args.afs_table, args.exome, args.label, args.bedtools_folder)

