import time

from securetea.lib.malware_analysis import globals
from flask import Flask, render_template
import pandas
import threading
import json

globals.initialize_flask()

app = Flask(__name__)

critical_df = None
alerts_dict = {}
djvu_html = ''


@app.route('/')
def home():
    global critical_df
    global alerts_dict
    global djvu_html

    while True:
        if globals.mal_file_dict == {}:
            pass
        else:
            break

        if not globals.djvu_files:
            pass
        else:
            break

        time.sleep(10)

    # print('Out of first while loop')

    '''
    mal_files being put to HTML
    '''
    mal_df_html = ''
    alerts_df_html = ''
    color = 'white'
    ctime = ''
    if globals.mal_file_dict != {}:
        mal_file_dict = globals.mal_file_dict
        mal_file_dict = json.loads(str(mal_file_dict).replace('\'', '\"'))
        mal_df = pandas.DataFrame(mal_file_dict).transpose()
        mal_df.columns = ['Detected', 'Undetected', 'Unsupported', 'Total', 'Report ID']
        # print("MAL DF")
        # print("MAL DF")
        # print("MAL DF")
        # print(mal_df.to_string())
        mal_df_html = mal_df.to_html()
        mal_df_html = 'document.getElementById("mal_df").innerHTML = `' + mal_df_html + '`;'
        '''
        mal_files being put to HTML ends
        '''
        '''
        ctime being put to HTML.
        ctime only exists when mal files are detected.
        '''
        ctime = 'Last Completed scan ended at ' + globals.ctime + '<br>Next scan in'
        ctime = 'document.getElementById("ctime").innerHTML = `' + ctime + '`;'
        '''
        ctime being put to HTML end
        '''


        '''
        alert_files being put to HTML
        '''
        color = 'white'
        for filename in mal_file_dict.keys():
            if mal_file_dict[filename][0] > 0:
                color = 'red'
                alerts_dict[filename] = mal_file_dict[filename]

        alerts_dict = json.loads(str(alerts_dict).replace('\'', '\"'))
        if alerts_dict != {}:
            alerts_df = pandas.DataFrame(alerts_dict).transpose()
            alerts_df.columns = ['Detected', 'Undetected', 'Unsupported', 'Total', 'Report ID']
            alerts_df_html = alerts_df.to_html()

        if alerts_dict != {}:
            alerts_df_html = 'document.getElementById("alerts_df").innerHTML = `' + alerts_df_html + '`;'
        else:
            alerts_df_html = 'document.getElementById("alerts_df").innerHTML = `No Alert files yet`;'

        # print(alerts_df.to_string())
        '''
        alerts_files being put to HTML end
        '''

    '''
    djvu_files being put to HTML
    '''
    djvu_html = ''
    if globals.djvu_files:
        print('INSIDE MAL FILE PRINT')
        for djvu_file in globals.djvu_files:
            djvu_html = djvu_html + str(djvu_file) + '<br>'

        djvu_html = 'document.getElementById("djvu_files").innerHTML = `' + djvu_html + '`;'
        print('DJVU HTML' + djvu_html)
    '''
    djvu_files being put to HTML end
    '''

    # write html to file
    text_file = open("./securetea/lib/malware_analysis/templates/origin.html", "r+")
    original_html = text_file.read()
    html = original_html
    text_file.close()

    html = html.replace('mal_df_js', mal_df_html)
    html = html.replace('alerts_df_js', alerts_df_html)
    html = html.replace('djvu_files_js', djvu_html)
    html = html.replace('ctime_js', ctime)
    # print('THIS IS HTMLLLL')
    # print('THIS IS HTMLLLL')
    # print('THIS IS HTMLLLL')
    # print(html)
    text_file.close()

    text_file = open("./securetea/lib/malware_analysis/templates/index.html", "w+")
    text_file.write(html)
    text_file.close()
    # print("ALERTS DF")
    # print("ALERTS DF")
    # print("ALERTS DF")
    # print(alerts_df.to_string())
    return render_template('index.html',
                           df_color=color)


def app_runner():
    globals.initialize_flask()
    app.config['TEMPLATES_AUTO_RELOAD'] = True
    app.run(debug=False)
