# This program is Free Software. You can use it under the terms of GNU GPL v3 or any later
# version of this license.

# This is a very basic program meant to be re-implemented and extented. It's based on
# the following article: https://odysee.com/@blenderdumbass:f/Web-Site-Score-System:4
# and gives the user an information about a requested site. And a Freedom score.

# First let's import a few things

import urllib3 # with this we will get a copy of the data from the internet
import json    # with this we will parse the data

# Now let's get the data

url = "https://notabug.org/jyamihud/FreeSoftwareActivism/raw/master/SiteScores/scores.json"
data = {}
try:
    # Trying to download the file and parsing it
    http = urllib3.PoolManager()
    resp = http.request('GET', url)
    data = json.loads(resp.data.decode("utf-8"))

    print("Data Loaded. Type site name to see info, or exit to exit.")
    
except Exception as e:

    # If the data isn't loaded, write that there was an error
    print("Can't load the data:", e)
    exit()


# A little compliter: Anything that comes into "commands" will
# be tabbable. 

commands = list(data.keys())
commands.append("exit")
commands.append("list")

def completer(text, state):
    options = [i for i in commands if i.startswith(text)]
    if state < len(options):
        return options[state]
    else:
        return None
# Importing this readline doesn't work everywhere.
# so no tabs for windows users, I guess.
try:
    import readline
    readline.parse_and_bind("tab: complete")
    readline.set_completer(completer)
except:
    print("NO TABS, SORRY!")


# Now that we have the data let's make a simple while loop
# and a person will type names of sistes to see them in data
# when typing exit, he will exit the loop, and the software
    
while True:
    c = input(": ")

    if c == "exit": # If typed exit
        exit()

    elif c in data.keys(): # If info about the site exists
        # just print a bunch of stuff about the site

         yn = {True:"YES", False:"NO "} # A little Trur to Yes, False to No translator
        
         print("------------------------------------------")
         print("|                                        |")

         # making center even, I gonna add this "e" which stands for "extra"         _
         e = " "                                                              # Here  \
         if len(c) % 2 == 0:   # basically odd or even ?                               #
             e = ""                                                                    #
             
         print("|"+" "*int(20-len(c)/2)+c.upper()+" "*int(20-len(c)/2)+  e  +"|")
         print("|                                        |")
         print("------------------------------------------")
         print("          SCORE: "+str(data[c]["score"]), "     ("+str(data[c]["score"]/8*100)+"%)")
         print("------------------------------------------")
         print("|    WORKS WITH TOR   |        "+yn[data[c]["0"]]+"       |")
         print("|   READABLE SOURCES  |        "+yn[data[c]["1"]]+"       |")
         print("|   FREE SOFTWARE JS  |        "+yn[data[c]["2"]]+"       |")
         print("|   WORKS WITHOUT JS  |        "+yn[data[c]["3"]]+"       |")
         print("|    NO DATA MINING   |        "+yn[data[c]["4"]]+"       |")
         print("|    NO DATA KEEPING  |        "+yn[data[c]["5"]]+"       |")
         print("|   FREE SOFT.SERVER  |        "+yn[data[c]["6"]]+"       |")
         print("|       FREE API      |        "+yn[data[c]["7"]]+"       |")
         print("------------------------------------------")
         print("|     LAST CHECKED    |    "+str(data[c]["last_reviewed"])+"    |" )
         print("|  CHECKED BY:                           |")
         print(" --------------")
         for i in data[c]["reviewed_by"]:
             print(" - "+str(i))
         print("------------------------------------------")
         note = str(data[c]["notes"])
         while note:
             e = ""
             if len(note) < 38:
                 e = " "*(38-len(note))
             print("| "+ note[:38]+e+" |")
             note = note[38:]
         print("------------------------------------------")
         
    # I want to add a way of viewing a high score thing.

    elif c == "list":

        # We gonna list by the order of scores. The highest should be near the
        # end, since they are ones we want to promote. And things like Google
        # with 1 score whould be printed immediatly. So the user will not get
        # to thise site.

        star = {False:" ", True:"#"}
        
        for s in range(-1, 8):
            s = s + 1

            for site in data:
                if data[site]["score"] == s:

                    # Let's make the star pattern
                    stars = ""
                    for i in range(8):
                        stars = stars + " | " + star[data[site][str(i)]]
                    
                    print(stars+" |   "+str(data[site]["score"])+"   | "+str(data[site]["score"]/8*100)+"% "+site)
                    print(" |---|---|---|---|---|---|---|---|-------|")
        print("   0   1   2   3   4   5   6   7   SCORE     %    WEBSITE")
        print()
        print(" 0: WORKS WITH TOR       4: NO DATA MINING")
        print(" 1: READABLE SOURCES     5: NO DATA KEEPING")
        print(" 2: FREE SOFTWARE JS     6: FREE SOFT.SERVER")
        print(" 3: WORKS WITHOUT JS     7: FREE API")

    # If not found any command let's search for what was imputed.

    elif c: # If something is in command.

        found = 0 # We are going to count ho many
        print("|-------------------------------------------|")
        for site in data:
            
            if c.lower() in site.lower() or c.lower() in data[site]["notes"].lower():
                found = found + 1

                # What part of the notes to cut out into the frame
                place = data[site]["notes"].lower().find(c.lower())
                # clearing it, to fit nicely.
                if c.lower() in site.lower() or place < 10:
                    place = 10
                if len(data[site]["notes"]) - place < 10:
                    place = place - 9

                # printing the site, notes peace, score in ####
                print ("| "+site[:15]+" "*max(0, 15-len(site)), " | ", data[site]["notes"][place-10:place+10]+"  | "+"#"*data[site]["score"])
                print("|-------------------------------------------|")

        # General info of how many found.
        print("        FOUND: "+str(found)+" WEBSITES")
