# %%
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 django.shortcuts import HttpResponseRedirect
from django.http import HttpResponse, JsonResponse
from django.utils import timezone
from django.urls import reverse
from django.core.files.storage import FileSystemStorage
from django.core.mail import send_mail
from django_tex.shortcuts import render_to_pdf

from celery.result import AsyncResult
import googlemaps
import timeit
import random
import json
import builtins as __builtin__
import csv

from leagues.celery import celery
from leagues.settings import EMAIL_DEFAULT_FROM, EMAIL_DEFAULT_TO
from leagues.settings import RUN_ENV, INSTANCE, DEBUG
from common.tasks import log_telegram
from common.functions import *
from scheduler.models import *
from scheduler.helpers import *
from scheduler.widgets import widget_context_kpis
from scheduler.solver.optimizer import optimize_2phases, optimize_sequentially
import scheduler.solver.optimizer as so
from draws.solver import optimize_draws

import time as timer

from qualifiers.helpers import import_globals


gmaps = googlemaps.Client(
    key='AIzaSyB76EhR4OqjdXHQUiTkHZC0Svx_7cPGqyU')

# %%

scenario = Scenario.objects.get(id=10)
# import_globals(scenario.season.id)
# teams = scenario.season.scheduler_teams.all()




# %%

new_teams = []
new_teams.append(("Group A", "Paxtakor Taschkent, Uzbekistan (UZB)",))
new_teams.append(("Group A", "al-Fayha FC, Saudi Arabia (KSA)",))
new_teams.append(("Group A", "Ahal FK, Turkmenistan (TKM)",))
new_teams.append(("Group A", "al Ain Club, United Arab Emirates (UAE)",))
new_teams.append(("Group B", "al-Sadd SC, Qatar (QAT)",))
new_teams.append(("Group B", "Nasaf Karschi, Uzbekistan (UZB)",))
new_teams.append(("Group B", "al-Faisaly, Jordan (JOR)",))
new_teams.append(("Group B", "Sharjah FC, United Arab Emirates (UAE)",))
new_teams.append(("Group C", "Ittihad FC, Saudi Arabia (KSA)",))
new_teams.append(("Group C", "Sepahan FC, Iran (IRN)",))
new_teams.append(("Group C", "al-Quwa al-Dschawiya, Iraq (IRQ)",))
new_teams.append(("Group C", "AGMK FC, Uzbekistan (UZB)",))
new_teams.append(("Group D", "al-Hilal, Saudi Arabia (KSA)",))
new_teams.append(("Group D", "Nassaji Mazandaran, Iran (IRN)",))
new_teams.append(("Group D", "Mumbai City FC, India (IND)",))
new_teams.append(("Group D", "Navbahor Namangan, Uzbekistan (UZB)",))
new_teams.append(("Group E", "Persepolis Teheran, Iran (IRN)",))
new_teams.append(("Group E", "al-Duhail SC, Qatar (QAT)",))
new_teams.append(("Group E", "FC Istiklol, Tajikistan (TJK)",))
new_teams.append(("Group E", "al-Nassr FC, Saudi Arabia (KSA)",))
new_teams.append(("Group F", "Jeonbuk Hyundai Motors, South Korea (KOR)",))
new_teams.append(("Group F", "Bangkok United, Thailand (THA)",))
new_teams.append(("Group F", "Lion City Sailors, Singapore (SGP)",))
new_teams.append(("Group F", "Kitchee SC, Hong Kong (HKG)",))
new_teams.append(("Group G", "Yokohama F. Marinos, Japan (JPN)",))
new_teams.append(("Group G", "Shandong Taishan, China (CHN)",))
new_teams.append(("Group G", "Kaya FC-Iloilo, Philippines (PHI)",))
new_teams.append(("Group G", "Incheon United, South Korea (KOR)",))
new_teams.append(("Group H", "Buriram United, Thailand (THA)",))
new_teams.append(("Group H", "Ventforet Kofu, Japan (JPN)",))
new_teams.append(("Group H", "Melbourne City FC, Australia (AUS)",))
new_teams.append(("Group H", "Zhejiang Professional FC, China (CHN)",))
new_teams.append(("Group I", "Ulsan Hyundai, South Korea (KOR)",))
new_teams.append(("Group I", "Kawasaki Frontale, Japan (JPN)",))
new_teams.append(("Group I", "Johor Darul Ta’zim FC, Malaysia (MAS)",))
new_teams.append(("Group I", "BG Pathum United FC, Thailand (THA)",))
new_teams.append(("Group J", "Wuhan Three Towns FC, China (CHN)",))
new_teams.append(("Group J", "Pohang Steelers, South Korea (KOR)",))
new_teams.append(("Group J", "Hà Nội FC, Vietnam (VIE)",))
new_teams.append(("Group J", "Urawa Red Diamonds, Japan (JPN)",))


# %%

pot_converter = {
    "A": 1,
    "B": 2,
    "C": 3,
    "D": 4,
    "E": 5,
    "F": 6,
    "G": 7,
    "H": 8,
    "I": 9,
    "J": 10,
}

Conference.objects.filter(scenario=scenario).delete()
for g in pot_converter.keys():
    Conference.objects.create(scenario=scenario, name=f"Group {g}", display_group=True, collapseInView=False)
Conference.objects.create(scenario=scenario, name='West', collapseInView=True, display_group=False)
Conference.objects.create(scenario=scenario, name='East', collapseInView=True, display_group=False)

pot = 1
for i,t in enumerate(new_teams):
    group = t[0]
    team_name = t[1].split(",")[0]
    team_country = t[1].split(",")[1].split("(")[0].strip()
    team_country_code = t[1].split(",")[1].split("(")[1].split(")")[0].strip()

    teamObj = Team.objects.filter(name=team_name, season=scenario.season).first()

    if not teamObj:
        gcountry = GlobalCountry.objects.filter(uefa=team_country_code)
        if not gcountry:
            gcountry = GlobalCountry.objects.filter(alpha3=team_country_code)
        if not gcountry:
            print("\t", "NOT FOUND")

        geocode_result = gmaps.geocode(team_name+" "+team_country)
        if len(geocode_result) > 0:
            location = geocode_result[0]['geometry']['location']
            print("\t", location)
        else:
            location = {'lat': 0, 'lng': 0}
            print("\t", "NOT FOUND")

        teamObj = Team.objects.create(
            name=team_name,
            country=team_country_code,
            season=scenario.season,
            active=True,
            latitude=location['lat'],
            longitude=location['lng'],
        )


    teamObj.shortname = teamObj.name[:5]
    teamObj.position = i+1
    teamObj.pot = pot
    teamObj.save()    
    pot += 1
    if pot > 4:
        pot = 1

    Conference.objects.get(scenario=scenario, name=group).teams.add(teamObj)

    if pot_converter[group.split(" ")[1]] <= 5:
        Conference.objects.get(scenario=scenario, name="West").teams.add(teamObj)
    else:
        Conference.objects.get(scenario=scenario, name="East").teams.add(teamObj)



# %%
