from utils import Logger
import requests, time, threading
from jobs.competition import Sportcompetition
from App.models import LeagueStanding


class HandleStanding():
    API_KEY = "be81c1bf6aa04f9f92d1de7b01e3b650"
    
    def run_thread(self):
        print("otuoo")
        # Start "start" method in a new thread
        # thread = threading.Thread(target=self.start, daemon=True)
        # thread.start()
        self.start()
        
    def start(self):
        for competition in Sportcompetition.available_standing:
            try:
                self.get_standing(competition)
            except Exception as e:
                Logger.warning("Something went wrong! Will retry in the next 1 min.")
                Logger.error(str(e))
                print("waiting for 60 seconds before retrying...")
                time.sleep(60)
                try: self.get_standing(competition)
                except: Logger.error("Error occured while fetching data!")
    
    def get_standing(self, comp):
        URL = f"https://api.football-data.org/v4/competitions/{comp[0]}/standings"
        headers = {"X-Auth-Token": self.API_KEY}
        print("Fetching standing for ", comp[1])
        
        response = requests.get(URL, headers=headers, timeout=15)

        current_standing = response.json()["standings"][0]

        if LeagueStanding.objects.filter(competition=comp[1]).exists():
            league_standing = LeagueStanding.objects.get(competition=comp[1])
            league_standing.standing = current_standing
            league_standing.save()
        else:
            league_standing = LeagueStanding.objects.create(
                competition=comp[1],
                standing=current_standing
            )
            league_standing.save()
