import yaml
import argparse
import os
import glob
import itertools
import pandas as pd
import sys
import time
import re
import yaml
import glob

# import plotly.graph_objects as go

from datetime import datetime
from jinja2 import Environment, FileSystemLoader

path = os.path.abspath(os.path.dirname(__file__))
template = os.path.join(path,"../templates/template.html")
#file_loader=FileSystemLoader(searchpath="../")

print("----------------------\n------------------")
print("----------------------\n------------------")
print(template)
print("----------------------\n------------------")
print("----------------------\n------------------")


#file_loader = FileSystemLoader('../templates')
#env = Environment(loader = file_loader)
#TEMPLATE_FILE = "../templates/template.html"
#print(os.getcwd())
#template = env.get_template(TEMPLATE_FILE)

templatevars= {}
###########################################################
'''
    Summary section
'''
###########################################################

wd = snakemake.params.wd

with open(os.path.join(wd,"config","config.yaml"),'r') as config_file:
    config = yaml.load(config_file, Loader=yaml.FullLoader)

summary = {}


summary["project"] = config["name"]
summary["date"] = datetime.now()#.strptime("%d/%m/%Y %H:%M:%S")
summary["project-path"] = config["project"]
summary["samples-path"] = config["samples"]
with open(config["samples"],'r') as samples_file:
    summary["#samples"] = len(yaml.load(samples_file,Loader=yaml.FullLoader).keys())

conf_dict = {}
for i in config.keys():
    if i not in ["name","project","samples","temp"]:
        conf_dict[i]=config[i]

summary["configuration"]=conf_dict

###########################################################
#
#    Pre-processing section
#
###########################################################

pre_process = {}
pre_process["multiqcreport"] = snakemake.input.multiqc

###########################################################
#
#    Assembly section
#
###########################################################

figs= {"total_length":"",
        "n_contigs":"",
        "n_longcontigs" :"",
        "n_verylongcontigs":"",
        "N50":"",
        "L50":""}



for i in snakemake.input.plots :
    name,ext = os.path.basename(i).split(".")[-2:]
    figs[name]=i

assembly = {}
assembly["figures"]=figs
#assembly["fig_png"]=figs_png


templatevars["summary"]=summary
templatevars["pre_process"]=pre_process
templatevars["assembly"]=assembly


#template = os.path.join(os.path.abspath(__file__),"../templates/template.html")
output = Environment(loader=FileSystemLoader(os.path.dirname(template))).get_template(os.path.basename(template)).render(templatevars)

with open(snakemake.output.report, "wb") as f:
	f.write(output.encode("utf-8"))

# output=template.render(templatevars)

# with open(snakemake.output.report,'w') as f:
#     f.write(output)
