import requests
import time
import json


URL = "http://192.168.88.247:4700/TabloData/GetTabloData"


def main():
    req = requests.get(URL)
    new_json = {
        "QUARTER": "",
        "TIMER": "",
        "TIMER_24": "",
        "TEAM1": "",
        "TEAM2": "",
        "SCORE1": "",
        "SCORE2": "",
        "FOUL1": "",
        "FOUL2": "",
    }

    temp = req.json()
    path_to_foul = "E:\TABLO\public_html obs — LETO 22 (09.10)"
    if len(temp) > 3:
        for i in temp:
            if i["ID"] == "43":
                new_json["TEAM1"] = i["VAL"]
            elif i["ID"] == "44":
                new_json["TEAM2"] = i["VAL"]
            elif i["ID"] == "TIMER":
                new_json["TIMER"] = i["VAL"].split(".")[0]
            elif i["ID"] == "21":
                new_json["SCORE1"] = i["VAL"]
            elif i["ID"] == "22":
                new_json["SCORE2"] = i["VAL"]
            elif i["ID"] == "23":
                foul1 = i["VAL"]
                if int(foul1) > 5:
                    new_json["FOUL1"] = path_to_foul + "\\left" + "\\5.png"
                else:
                    new_json["FOUL1"] = path_to_foul + "\\left" + f"\{i['VAL']}.png"
            elif i["ID"] == "24":
                foul2 = i["VAL"]
                if int(foul2) > 5:
                    new_json["FOUL2"] = path_to_foul + "\\right" + "\\5.png"
                else:
                    new_json["FOUL2"] = path_to_foul + "\\right" + f"\{i['VAL']}.png"
            elif i["ID"] == "5":
                val = ""
                if i["VAL"] == "1":
                    val = "1ST"
                elif i["VAL"] == "2":
                    val = "2ND"
                elif i["VAL"] == "3":
                    val = "3RD"
                elif i["VAL"] == "4":
                    val = "4TH"
                else:
                    val = "OT" + str(int(i["VAL"]) - 4)
                new_json["QUARTER"] = val
            elif i["ID"] == "4":
                new_json["TIMER_24"] = i["VAL"]
        with open("E:\\TABLO\\timer_basketball.json", "w", encoding="utf-8") as file:
            json.dump([new_json], file, ensure_ascii=False, indent=4)
        print(new_json)


if __name__ == "__main__":
    try:
        while True:
            try:
                main()
                time.sleep(0.1)
            except Exception as ex:
                print(ex)
    except KeyboardInterrupt:
        exit(1)
