import os
from shutil import copyfile
import json

from Spitzer import command
from Spitzer.result.result import add
from Spitzer.config import config
from Spitzer.chache import chache

category = ['safe']

def exploit(url, _):
    if url.startswith('http://'):
        return
        
    print('testssl')
    chache.remove_file('testssl.html')
    chache.remove_file('testssl.json')
    testssl = config.get_data('testssl')
    cmd = [testssl, '--htmlfile', chache.get_path() + 'testssl.html', '--jsonfile', chache.get_path() + 'testssl.json', url]
    print(cmd)
    command.run(cmd, capture_output=False)

    html = chache.read_file('testssl.html')

    #find the colorcodes for red and/or orange in the html
    #orange: #cdcd00
    #red: #cd0000

    if '#cdcd00' in html or '#cd0000' in html:
        if '#cd0000' in html:
            print('[*] testssl found errors') 
        else:
            print('[*] testssl gave warnings')
        
        #copy html to working folder
        src = chache.get_path() + 'testssl.html'
        dst = os.getcwd() + '/' + 'testssl.html'
        copyfile(src, dst)
        print('[-] Placed testssl.html in ' + os.getcwd())

    parse_json()

def parse_json():

    #read file
    j = open(chache.get_path() + 'testssl.json', 'r').read()
    results = json.loads(j)

    options = ['LOW', 'MEDIUM', 'HIGH']


    for find in results:
        if any(option in find['severity'] for option in options):
            host = find['ip'].split('/')[0]
            finding = find['id'] + ' ' + find['finding']
            add(host, 'testssl', finding)