from report import bam, fasta, tabix
import json
from os.path import splitext
import os
from report import data_uri

## read JSON file
## for each mutation:
       ## calculate panning region around POS
       ## extract bamfile slice
       ## extract bedfile slice
       ## extract fasta slice
       ## create html report
SCRIPT_PATH = os.path.abspath(os.path.dirname(__file__))
QUOTES = {"'", '"'}

def get_basename(filepath):
    return(os.path.basename(filepath))

def create_report(url,bam_slice,bed_slice,fasta_slice,genomic_region,sample_name):
    if not url.startswith('/'):
        url = os.path.join(SCRIPT_PATH, url)
    basedir = os.path.dirname(url)
    data_uris = {}
    with open(url, "r") as f:
        data = f.readlines()

    for i, line in enumerate(data):
        j = line.find('<!-- start igv report here -->')
        if j >= 0:
            space = ' ' * j
            report_start = i + 1
            break
    else:
        print("file must contain the line \"<!-- start igv report here -->\"")
        return

    report_data = data[report_start:]
    report_data=[r.replace("sampleInfo.SAMPLE",'"'+sample_name+'"') for r in report_data]
    report_data=[r.replace("seq_name:start-end",genomic_region) for r in report_data]
    report_data=[r.replace("fasta.url",get_basename(fasta_slice)) for r in report_data]
    report_data=[r.replace("recalibrated.bam",get_basename(bam_slice)) for r in report_data]
    report_data=[r.replace("refGene.sort.bed",get_basename(bed_slice))for r in report_data]
    for line_index, line in enumerate(report_data):
        i=line.lower().find('url:')
        if i >= 0:
            i += 4
            while line[i] not in QUOTES and i < len(line):
                i += 1
            i += 1
            start = i
            while line[i] not in QUOTES and i < len(line):
                i += 1
            filename = line[start:i]
            report_data[line_index] = line[:start - 1] + 'data["' + filename + '"]' + line[i+1:]
            data_uris[filename] = data_uri.file_to_data_uri(os.path.join(basedir, filename))


    new_html_data = data[:report_start] + data_uri.create_data_var(data_uris, space) + report_data
    output_name = os.path.join(basedir, url[:-5] + '_report_'+genomic_region+url[-5:])
    with open(output_name, 'w') as f:
        f.writelines(new_html_data)

if __name__ == "__main__":
    import argparse
    parser = argparse.ArgumentParser()
    parser.add_argument("--pan_region", type=int ,help="number of bases to extarct around each mutation")
    parser.add_argument("--html_template", help="the html file to be converted")
    parser.add_argument("--fasta_file", help="Genome fasta file")
    args = parser.parse_args()

    with open("example/MI_viewer/mutation_inspector.json","r") as json_data:
        data=json.load(json_data)

    if data:
        mutations=data["SNV"]
        for mut in mutations:
            start=int(mut["POS"])-args.pan_region
            end=int(mut["POS"])+args.pan_region
            genomic_region=mut["CHROM"]+":"+str(start)+"-"+str(end)
            bam_slice=bam.make_region_bam("example/MI_viewer/recalibrated.bam",genomic_region)
            bed_slice=tabix.get_data("example/MI_viewer/refGene.sort.bed.gz",genomic_region)
            fasta_slice=fasta.extract_fasta_seq(args.fasta_file,genomic_region)
            sample_name=data["SAMPLE"]
            create_report(args.html_template,bam_slice,bed_slice,fasta_slice,genomic_region,sample_name)
