# %%
PROJECT_PATH = '/home/md/Work/ligalytics/leagues_stable/'
import os, sys
sys.path.insert(0, PROJECT_PATH)
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "leagues.settings")
os.environ["DJANGO_ALLOW_ASYNC_UNSAFE"] = "true"


from leagues import settings
settings.DATABASES['default']['NAME'] = PROJECT_PATH+'/db.sqlite3'



import django
django.setup()

from scheduler.models import *
from pulp import *

from django.urls import get_resolver
from django_tex.shortcuts import render_to_pdf


from common import urls
from referees import urls
from qualifiers import urls

from django.core.handlers.base import BaseHandler  
from django.test.client import RequestFactory  
from scheduler.widgets import widget_context_games_reduced



# %%

scenario = Scenario.objects.get(id=14)

dayObjects = Day.objects.filter(season=scenario.season)
rounds = dict(scenario.gamesOfRound()).keys() 
teams = scenario.teams_dict()
timeslots = {str(t.id):t.name for t in scenario.season.timeslots.all()}

getTeamById = {}
teamObj = Team.objects.filter(season=scenario.season)

for t in teamObj:
    getTeamById[str(t.id)] = t
    if (t.logo.name.split('.')[-1] != 'png'):
        os.rename(f'{t.logo.path}',f'{t.logo.path}.png')
        t.logo.name = f'{t.logo.name}.png'
        t.save()

# %%

getDayById = {}
for d in dayObjects:
    getDayById[d.id] = d

list_games = []
list_rounds = {r:defaultdict(lambda:[]) for r in rounds}
list_days = defaultdict(lambda:[])
games = {}
cntr = 0

x_pos = 0
y_pos = 0
last_y_pos = 0
page_break = 9999

for r in rounds:
    games[r] = widget_context_games_reduced(scenario,r)  
    games_per_round = 0

    if last_y_pos + sum([len(i) for i in games[1]['gamesOfDay'].values()]) > 60:
        page_break = x_pos
        last_y_pos = 0
        x_pos = 0
    
    y_pos = last_y_pos+10

    for day,gamesPerDay in games[r]['gamesOfDay'].items():
        if not gamesPerDay:
            continue
        for game in gamesPerDay:           
            games_per_round += 1
            cntr += 1
            t1 = getTeamById[game[1]]
            t2 = getTeamById[game[2]]
            game_details = (f'{cntr}','',f'\includegraphics[width=0.2cm]{{{t1.logo.path}}}',f'{t1.shortname}', f'\includegraphics[width=0.2cm]{{{t2.logo.path}}}', f'{t2.shortname}',x_pos % 5,y_pos,game[4])
            list_games.append(game_details)
            list_rounds[r][(day,str(getDayById[day]))].append(game_details)
            list_days[str(getDayById[day])].append(game_details)
            y_pos += 1
        y_pos += 3
    x_pos += 1

    if x_pos % 5 == 0:
        last_y_pos = y_pos

    if x_pos >= page_break:
        last_y_pos = 0
        x_pos = 0

            

# %%


template_name = 'latex/season_overview.tex'
context = {
    'scenario': scenario, 
    'rounds': list_rounds,
    'page_break':page_break,
}
response = render_to_pdf(None, template_name, context, filename='test.pdf')



with open("response.pdf", "wb") as f:
    f.write(response.content)
# %%

