#!/usr/bin/venv python
# -*- coding: utf-8 -*-

from datetime import datetime
from os import mkdir
from config import VT_ATTRIBUTES_MAPPING
import jinja2


def generateHtmlReport(data):
    env = jinja2.Environment(
        loader=jinja2.FileSystemLoader("reports/templates"),
        autoescape=jinja2.select_autoescape()
    )

    _queriesReport(data['queries'], env)
    _graphicsReport(data['graphics'], env)
    _vtReport(data['vt'], env)
    _dnsTunnelingReports(data['dnstunneling'], env)

def _indexReport():
    pass

def _queriesReport(queries, env):
    """
    This function generate the report for queries
    """
    today = getTodayDate()
    dataJinja2 = dict()
    dataJinja2['title'] = 'Queries'
    dataJinja2['year'] = '2023'
    dataJinja2['queries'] = queries

    tmpl = env.get_template('queries.html.j2')

    render = tmpl.render(data=dataJinja2)

    with open(f"reports/{today}/reports_queries.html", "w") as f:
        f.write(render)

def _graphicsReport(graphics, env):
    today = getTodayDate()

    dataJinja2 = dict()
    dataJinja2['title'] = 'Graphics'
    dataJinja2['year'] = '2023'
    dataJinja2['graphics'] = graphics

    tmpl = env.get_template('graphics.html.j2')

    render = tmpl.render(data=dataJinja2)

    with open(f"reports/{today}/reports_graphics.html", "w") as f:
        f.write(render)

def _vtReport(vt, env):
    today = getTodayDate()
    # For testing
    #vt = list()
    #vt.append({
    #    'ip': '1.2.3.4',
    #    'asn': 3215,
    #    'as_owner': 'Orange',
    #    'continent': 'EU',
    #    'country': 'FR',
    #    'last_analysis_date': 1686839532,
    #    'regional_internet_registry': 'RIPE NCC',
    #    'network': '1.2.3.0/24'
    #})
    #vt.append({
    #    'ip': '2.2.2.1',
    #    'asn': 3215,
    #    'as_owner': 'Orange',
    #    'continent': 'EU',
    #    'country': 'FR',
    #    'last_analysis_date': 1686839532,
    #    'regional_internet_registry': 'RIPE NCC',
    #    'network': '2.2.2.0/24'
    #})
    #vt.append({
    #    'ip': '3.3.3.1',
    #    'asn': 3215,
    #    'as_owner': 'Orange',
    #    'continent': 'EU',
    #    'country': 'FR',
    #    'last_analysis_date': 1686839532,
    #    'regional_internet_registry': 'RIPE NCC',
    #    'network': '3.3.3.0/24'
    #})

    dataJinja2 = dict()
    dataJinja2['title'] = 'VirusTotal'
    dataJinja2['year'] = '2023'
    dataJinja2['vt'] = list()

    tmpl = env.get_template('vt.html.j2')

    body = str()

    for entry in vt:
        vtEntry = dict()
        if 'error' not in entry:
            for vt in VT_ATTRIBUTES_MAPPING.keys():
                try:
                    vtAttributes = VT_ATTRIBUTES_MAPPING[vt]
                    if 'date' in vtAttributes:
                        value = datetime.fromtimestamp(int(entry[vt]))
                    else:
                        value = entry[vt]
                    vtEntry[vt] = value
                except KeyError:
                    pass
            dataJinja2['vt'].append({
                'ip': entry['ip'],
                'data': vtEntry
            })

    render = tmpl.render(data=dataJinja2)

    with open(f"reports/{today}/reports_vt.html", "w") as f:
        f.write(render)

def _dnsTunnelingReports(dnstunneling, env):
    today = getTodayDate()

    dataJinja2 = dict()
    dataJinja2['title'] = 'DNS Tunneling'
    dataJinja2['year'] = '2023'
    dataJinja2['dnstunneling'] = dnstunneling

    tmpl = env.get_template('dnsTunneling.html.j2')

    render = tmpl.render(data=dataJinja2)

    with open(f"reports/{today}/reports_dns_tunneling.html", "w") as f:
        f.write(render)

def createReportsDirectory():
    """
    This function will create the reports directory
    Return the report name or None if failed
    """
    today = getTodayDate()
    name = f"reports/{today}"
    try:
        mkdir(name)
    except FileExistsError: 
        print("Reports directory already created")
        return name
    return name

def getTodayDate():
    """
    This function genrate the today datetime at this format:
        year_month_day
    """
    return datetime.now().isoformat()[0:10].replace("-", "_")
