# THIS SOFTWARE IS A PART OF FREE COMPETITOR PROJECT
# THE FOLLOWING SOURCE CODE I UNDER THE GNU
# AGPL LICENSE V3 OR ANY LATER VERSION.

# This project is not for simple users, but for
# web-masters and a like, so we are counting on
# your ability to set it up and running.

from modules import search

def html(page, json):

    # This function adds a rendering of the json into the page

    free = False
    if "licenses" in json and json["licenses"]:
        free = True

    page = page + "\n <h1>"
    try:
        page = page + '\n<img src="'+ json["links"]["icon"] + '" alt="Logo" style="width:50px;">'
    except:
        pass

    # Name / Website link
    name = json.get("names",["Unknown"])[0]
    

    page = page + "\n" + name 

    page = page + "</h1>"
        
    # Few words about it
    page = page + "<p>"+json.get("comment","")+"</p>"

    # Links
    website = json.get("links",{}).get("website", "")
    if free and website:
        page = page + """
        <form action=\""""+website+"""\">
            <button type="submit">Website</button>
        </form>
       """

    git = json.get("links",{}).get("git", "")
    if git:
        page = page + """
        <form action=\""""+git+"""\">
            <button type="submit">Source Code</button>
        </form>
       """

    wikipedia = json.get("links",{}).get("wikipedia", "")
    if wikipedia:
        page = page + """
        <form action=\""""+wikipedia+"""\">
            <button type="submit">Wikipedia</button>
        </form>
       """

    
    return page

def suggestions(page, json):

    # This function will render suggestions

    page = page + "<br><br><h1>Replacements:</h1><br><br>"

    print("json request")
    
    found = search.suggest(json)
    print("json received", len(found))
    
    for i in found:

        print(i[-1].get("names",["no name"])[0], "Drawing")
        
        free = False
        if "licenses" in i[-1] and i[-1]["licenses"]:
            free = True
        
        print(i[-1].get("names", ["nothing"])[0])
        if not i[0] or i[-1] == json or not free:
            continue
        page = page + "<br><br>"
        page = html(page, i[-1])

    return page