import os
from os.path import join
from settings import settings
import shutil

def Copy_BQSR_bam(bqsr_cosmos_folder, out_dir, bam_name, sample):
    bam_chunk=[]
    sample="SM:"+sample
    print sample
    # Create temp_dir and out_dir if don't exist
    if not os.path.exists(out_dir):
            os.makedirs(out_dir)
    
    # Search for .vcf files in the VQSR folder generated by Cosmos and saved on the s3 bucket 
    for root, subFolders, files in os.walk(bqsr_cosmos_folder):
        for file in files:
            check_sample=0
            filePath = root + '/' + file
            if filePath.endswith(".bam"):
                header = out_dir + '/' + file+"_temp"
                cmd= "samtools view -H "+filePath+" > "+header
                print cmd
                os.system(cmd)
                with open(header) as f:
                    for line in f:
                        #print line
                        if sample in line:
                            check_sample=1
                cmd="rm "+header
                os.system(cmd)
            if check_sample==1:
                bam_chunk.append(filePath)
    chunk=' '.join(bam_chunk)
    print chunk
    out_bam=join(out_dir,bam_name)
    cmd="samtools merge "+out_bam+" "+chunk
    print cmd
    os.system(cmd)

def Stat_Bam(out_dir,file_in,file_stat):
    if not os.path.exists(out_dir):
        os.makedirs(out_dir)
    print file_in
    file_out=open(join(out_dir,file_stat),'w')
    temp_file=file_stat+"_tmp"
    os.system("samtools view -c "+file_in+" > "+join(out_dir,temp_file))
    with open(join(out_dir,temp_file)) as f:
        content = f.readline()
        total_read = content.rstrip()
        file_out.write("TOTAL READS\t"+total_read+"\n")
    # Remove file_tmp
    os.system("rm "+join(out_dir,temp_file))
    # Unmapped reads
    os.system("samtools view -cf 4 "+file_in+" > "+join(out_dir,temp_file))
    with open(join(out_dir,temp_file)) as f:
        content = f.readline()
        unmapped_read = content.rstrip()
        file_out.write("UNMAPPED READS\t"+unmapped_read+"\n")        
    os.system("rm "+join(out_dir,temp_file))
    mapped_reads=float(total_read)-float(unmapped_read)
    file_out.write("MAPPED READS\t"+str(mapped_reads)+"\n")        
    percentage_unmapped_reads=float(unmapped_read)*100/float(total_read)
    file_out.write("% UNMAPPED READS\t"+str(percentage_unmapped_reads))        
    file_out.close()
    
    fastqc=settings.setting['fastqc']
    out_dir_fastqc=join(out_dir,"FastQC")
    if not os.path.exists(out_dir_fastqc):
        os.makedirs(out_dir_fastqc)
    os.system("perl "+fastqc+" "+file_in+" -o "+out_dir_fastqc)
        
