from datetime import datetime, timedelta
from time import sleep
import pytz
import json
import requests
import sys

def sortevents(leaguedata, league):

    games = []
    haslive = False

    for event in leaguedata['events']:

        event_desc = event['status']['type']['shortDetail']  # use this to display time and quarter on ticker
        event_date = event['date'].split('T')[0]
        event_liveOrNot = event['status']['type']['state'] # use this to determine if game has ended or not
        if event_liveOrNot == 'in':
            haslive = True
        has_live = 'has_live'
        no_upcoming = 'no_upcoming'

        for home_away in event['competitions']:
            for home_away2 in home_away['competitors']:
                if home_away2['homeAway'] == 'away':
                    if home_away2['team']['displayName'] == 'Washington Commanders':
                        away_team = 'Washington'
                    else:
                        away_team = home_away2['team']['displayName']
                    away_score = home_away2['score']
                else:
                    if home_away2['team']['displayName'] == 'Washington Commanders':
                        home_team = 'Washington'
                    else:
                        home_team = home_away2['team']['displayName']
                    home_score = home_away2['score']

        if datetime.now(pytz.utc).strftime("%Y-%m-%d") == event['date'].split('T')[0] or event['date'].split('T')[0] <= (datetime.strptime(datetime.now(pytz.utc).strftime("%Y-%m-%dT%H:%MZ"), "%Y-%m-%dT%H:%MZ") + timedelta(days=1)).strftime("%Y-%m-%dT%H:%MZ").split('T')[0]:
            games.append({
                'home_team': home_team,
                'home_score': home_score,
                'away_team': away_team,
                'away_score': away_score,
                'time': event_desc,
                'date': event_date,
                'isLive': event_liveOrNot
            })
    return games, haslive, has_live, no_upcoming


f = open('csv/live_nba.json', 'r')
all_settings = json.load(f)
f.close()

nba_url = "https://site.api.espn.com/apis/site/v2/sports/basketball/nba/scoreboard"

time_now = datetime.now(pytz.utc)
time_now2 = time_now.strftime("%Y-%m-%dT%H:%MZ")

NBA_live_now = False
NBA_games_today = False
NBA_events = []
NBA_fifteenmin = False
games_happened = False

try:
    nba_response = requests.get(nba_url)
    nba_data = nba_response.json()
except:
    sleep(120)
    nba_response = requests.get(nba_url)
    nba_data = nba_response.json()

for event in nba_data['events']:
    if event['status']['type']['state'] == 'in':
        NBA_live_now = True
    if time_now2.split('T')[0] <= event['date'].split('T')[0] and event['date'].split('T')[0] <= (datetime.strptime(time_now2, "%Y-%m-%dT%H:%MZ") + timedelta(days=1)).strftime("%Y-%m-%dT%H:%MZ").split('T')[0]:
        NBA_events.append(event['date'])
        NBA_games_today = True
        if NBA_live_now is False and ((datetime.strptime(event['date'], "%Y-%m-%dT%H:%MZ") + timedelta(minutes=20)).strftime("%Y-%m-%dT%H:%MZ") >= datetime.now(pytz.utc).strftime("%Y-%m-%dT%H:%MZ")) and (event['date'] <= datetime.now(pytz.utc).strftime("%Y-%m-%dT%H:%MZ")):
            NBA_fifteenmin = True


while True:
    f = open('csv/live_nba.json', 'r')
    all_settings = json.load(f)
    f.close()

    if NBA_live_now:
        try:
            nba_response = requests.get(nba_url)
            nba_data = nba_response.json()
            nba_sorted = sortevents(nba_data, 'NBA')
            all_settings['leagues']['NBA'] = nba_sorted
            games_happened = True

            if nba_sorted[1]:
                NBA_live_now = True
            else:
                NBA_live_now = False         

            f = open('csv/live_nba.json', 'w+')
            json.dump(all_settings, f)
            f.close()

            sleep(120)
        except:
            sleep(120)


    elif NBA_fifteenmin:
        for _ in range (10):
            try:
                nba_response = requests.get(nba_url)
                nba_data = nba_response.json()
                nba_sorted = sortevents(nba_data, 'NBA')
                all_settings['leagues']['NBA'] = nba_sorted

                f = open('csv/live_nba.json', 'w+')
                json.dump(all_settings, f)
                f.close() 
                sleep(120)
            except:
                sleep(120)

        if nba_sorted[1]:
            NBA_live_now = True
            NBA_fifteenmin = False
            games_happened = True                     

        else:
            NBA_live_now = False
            NBA_fifteenmin = False

    else:
        # NBA_events = ['2022-12-06T13:13Z', '2022-12-06T20:30Z', '2022-12-06T21:00Z', '2022-12-06T23:50Z']
        # NFL_events = ['2022-12-05T14:54Z']

        NBA_events2 = []

        try:
            for event in NBA_events:
                if event >= datetime.now(pytz.utc).strftime("%Y-%m-%dT%H:%MZ"):
                    NBA_events2.append(event)
                    NBA_games_today = True
            next_NBA = min(NBA_events2)
            d = datetime.strptime(next_NBA, "%Y-%m-%dT%H:%MZ")
            NBA_time_left = (d - (datetime.strptime(datetime.now(pytz.utc).strftime("%Y-%m-%dT%H:%MZ"), "%Y-%m-%dT%H:%MZ"))).total_seconds()
            all_settings['leagues']['NBA'][3] = next_NBA
            f = open('csv/live_nba.json', 'w+')
            json.dump(all_settings, f)
            f.close()

        except:
            NBA_games_today = False
            next_NBA = []
            all_settings['leagues']['NBA'][3] = 'no_upcoming'
            f = open('csv/live_nba.json', 'w+')
            json.dump(all_settings, f)
            f.close()
            pass   

        if NBA_games_today:
            sleep(NBA_time_left)
            NBA_fifteenmin = True


    if NBA_live_now is False and NBA_games_today is False and games_happened is True:
        sleep(7200)

        all_settings['leagues']['NBA'][2] = 'no_live'
        all_settings['leagues']['NBA'][3] = 'no_upcoming'
        f = open('csv/live_nba.json', 'w+')
        json.dump(all_settings, f)
        f.close()
        break


    if NBA_live_now is False and NBA_games_today is False and games_happened is False:
        all_settings['leagues']['NBA'][2] = 'no_live'
        all_settings['leagues']['NBA'][3] = 'no_upcoming'
        f = open('csv/live_nba.json', 'w+')
        json.dump(all_settings, f)
        f.close()
        break
