from utils import Logger
import requests, time
from jobs.competition import Sportcompetition
from App.models import LeagueStanding



class HandleStanding():
    API_KEY = "be81c1bf6aa04f9f92d1de7b01e3b650"
    
    def __init__(self):
        self.start()
        
    def start(self):
        for competition in Sportcompetition.available_standing:
            try:
                self.get_standing(competition)
            except:
                Logger.warning("Something went wrong! \nWill retry in the next 1min.")
                # 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)
        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()