# %%
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'
settings.DATABASES['default']['ENGINE'] = 'django.db.backends.postgresql_psycopg2'
settings.DATABASES['default']['HOST'] = '0.0.0.0'
settings.DATABASES['default']['PORT'] = '5432'
settings.DATABASES['default']['USER'] = 'postgres'
settings.DATABASES['default']['PASSWORD'] = 'secret123'
settings.DATABASES['default']['NAME'] = 'mypgsqldb'
settings.DATABASES['default']['ATOMIC_REQUESTS'] = False
settings.DATABASES['default']['AUTOCOMMIT'] = True
settings.DATABASES['default']['CONN_MAX_AGE'] = 0
settings.DATABASES['default']['CONN_HEALTH_CHECKS'] = False
settings.DATABASES['default']['OPTIONS'] = {}

os.environ["XPRESSDIR"] = "/opt/xpressmp"
os.environ["XPRESS"] = "/opt/xpressmp/bin"
os.environ["LD_LIBRARY_PATH"] = os.environ["XPRESSDIR"] + "/lib"
os.environ["DYLD_LIBRARY_PATH"] = os.environ["XPRESSDIR"] + "/lib"
os.environ["SHLIB_PATH"] = os.environ["XPRESSDIR"] + "/lib"
os.environ["LIBPATH"] = os.environ["XPRESSDIR"] + "/lib"
os.environ["PYTHONPATH"] = os.environ["XPRESSDIR"] + "/lib"
os.environ["CLASSPATH"] = os.environ["XPRESSDIR"] + "/lib/xprs.jar"
os.environ["CLASSPATH"] = os.environ["XPRESSDIR"] + "/lib/xprb.jar" + os.pathsep + os.environ["CLASSPATH"]
os.environ["CLASSPATH"] = os.environ["XPRESSDIR"] + "/lib/xprm.jar" + os.pathsep + os.environ["CLASSPATH"]
os.environ["PATH"] = os.environ["XPRESSDIR"] + "/bin" + os.pathsep + os.environ["PATH"]


import django
django.setup()

from scheduler.models import *
import pulp
from pulp import lpSum, value, XPRESS, GUROBI, PULP_CBC_CMD
from django.db.models import Q
from django.template.loader import render_to_string

from qualifiers.models import *
from common.models import GlobalTeam, GlobalCountry
from scheduler.models import Season, Scenario, Team, DayObj, CountryClash, Country

from qualifiers.draws import groupTeams, optimize_inversions4
from scheduler.solver.tasks.optimize import optimize

import random
import time
import json
import csv
import networkx as nx
import matplotlib.pyplot as plt
from datetime import timedelta
# %%

from django.contrib.sessions.models import Session

scenario = Scenario.objects.get(id=8506)
season = scenario.season
days = Day.objects.filter(season=scenario.season)
teams = Team.objects.filter(season=scenario.season)
federation = FederationMember.objects.filter(season=scenario.season).first().federation
stadiums = Stadium.objects.filter(federation=federation)
stadiumtimeslotblockings = StadiumTimeSlotBlocking.objects.filter(stadiumTimeSlot__stadium__in=stadiums)

# %%

getTeamByName = {}
for t in teams:

    if t.name == "AHOUD Devils Nijmegen U9":
        name = "Nijmegen Devils"
    elif t.name == "Unis Flyers Heerenveen U7/U9/U11":
        name="UNIS Flyers Heerenveen"
    elif t.name == "IJCU Utrecht U9/U11":
        name="Utrecht Dragons"
    else:
        name = t.name.split("U7")[0].split("U9")[0].split("U11")[0].strip()
    getTeamByName[name] = t

getStadiumByName = {}
for s in stadiums:
    if s.name == "IJssportcentrum Eindhoven (kleine hal)":
        name = "IJssportcentrum Eindhoven (Kleine hal)"
    elif s.name == "Sportiom":
        name = "Den Bosch"
    else:
        name = s.name
    getStadiumByName[name] = s


# %%

stsb = []
with open('LOS-ScheduleImportTemplate_EN-U9.csv', newline='') as csvfile:
    reader = csv.reader(csvfile)
    next(reader, None)
    next(reader, None)
    for row in reader:
        # print(row)
        
        raw_dayobj = datetime.datetime.strptime(row[3],'%m/%d/%Y')
        raw_time = row[4]
        raw_stadium= row[7]
        raw_team1 = row[8].split("U9")[0].strip()
        raw_team2 = row[9].split("U9")[0].strip()

        # day
        day = days.filter(day=raw_dayobj.strftime('%Y-%m-%d')).first()
        if not day:
            print("\tERROR",day)
            break

        # teams
        team1 = getTeamByName.get(raw_team1, None)
        team2 = getTeamByName.get(raw_team2,None)

        if not team1 or not team2:
            print("\tERROR",team1,team2)
            break

        # stadium
        stadium = None
        for s in getStadiumByName.keys():
            if raw_stadium in s:        
                stadium = getStadiumByName[s]
                break                
        
        if not stadium:
            print("\tERROR",stadium)
            break

        # timeslot
        weekday = raw_dayobj.strftime('%A')+"s"
        start = datetime.time(int(raw_time.split(":")[0]),int(raw_time.split(":")[1]))
        end = datetime.time(int(raw_time.split(":")[0])+2 % 24,int(raw_time.split(":")[1]))
        timeslot = StadiumTimeSlot.objects.filter(stadium=stadium,weekday=weekday,start=start,end=end)
        if timeslot.count() > 1:
            print("ERROR",stadium,weekday,start,end)
            break
        else:
            timeslot = timeslot.first()
        if not timeslot:
            club = StadiumTimeSlot.objects.filter(stadium=stadium).first().club
            print("Missing",stadium,weekday,start,end)
            timeslot = StadiumTimeSlot.objects.create(
                stadium=stadium,
                club=club,
                weekday=weekday,
                start=start,
                end=end
            )



        stsb.append(StadiumTimeSlotBlocking(stadiumTimeSlot = timeslot,
            homeTeam = team1,
            awayTeam = team2,
            day = day.day,
            )
        )


StadiumTimeSlotBlocking.objects.bulk_create(stsb)

# %%




