from utils import Logger
import requests
from jobs.competition import Sportcompetition
from App.models import Matches


class HandleFixtures:
    def __init__(self):
        self.start()
        
    def start(self):
        for competition in Sportcompetition.competitions:
            try:
                self.get_fixtures(competition)
            except:Logger.error("Something went wrong!")
            
    def get_fixtures(self, competition):
        url = f"https://api.the-odds-api.com/v4/sports/{competition['competition']}/odds?api_key={competition['api_key']}&regions=uk&dateFormat=iso&markets=h2h,spreads,totals&oddsFormat=decimal"
        try:
            print(f"Fetching {competition['name']} fixtures...")
            res = requests.get(url, timeout=15)
            data = res.json()
            for match in data:
                if Matches.objects.filter(match_id=match["id"]).exists():
                    continue
                else:
                    self.create_match(match)
        except Exception as e:
            print(e)
            Logger.error("Something went wrong!")
            
    def create_match(self, match):
        for a in match['bookmakers'][0]['markets'][0]['outcomes']:
            if a['name'] == match['home_team']:
                home_odd = a['price']
            if a['name'] == 'Draw':
                draw_odd = a['price']
            if a['name'] == match['away_team']:
                away_odd = a['price']
        
        new_match = Matches.objects.create(
            match_id = match["id"],
            home_team = match["home_team"],
            away_team = match["away_team"],
            commencement_time = match["commence_time"],
            competition = match["sport_key"],
            isleague = True if not match["sport_key"] in Sportcompetition.cups else False,
            
            home_win = home_odd,
            draw = draw_odd,
            away_win = away_odd,
            bookmaker = match['bookmakers'][0]['key']
            
        )
        new_match.save()
        Logger.success(f"Match {match['id']} created successfully.")
    
    
