from scheduler.models import *
from scheduler.helpers import *
from scheduler.solver.optimizer import optimize_2phases, optimize_simulate, optimize_sequentially

from celery.result import AsyncResult

from leagues.settings import RUN_ENV
from leagues.celery import celery



class UefaSimulator:
    
    def __init__(self,scenario_id):
        self.scenario = Scenario.objects.get(id=scenario_id)
        self.param = {
            "NAME":"undefined",
            "SIMC":0,
            "OPPONENTS":"",
            "RUNMODE":"",
            "LOCALSEARCHTIME":0,
            "RESET":False,
            "CREATE_ONLY":False,
            "SIM_ONLY":False,
            "UCL24PATTERNS":False,
            "KEEP_SCENARIOS":False,
        }
        self.param.update(self.scenario.parse_sim_script())
        
    
    def simulate(self):

        if self.param['RESET'] == "True":
            self.scenario.simulation_scenarios.all().delete()
            setup = {
                'STATS': {
                    "STARTED":datetime.datetime.now().strftime("%d.%m.%Y, %H:%M:%S"),
                    "FINISHED":0,
                }
            }
        else: 
            setup = json.loads(self.scenario.sim_report)
            setup['STATS'] = {
                "STARTED":datetime.datetime.now().strftime("%d.%m.%Y, %H:%M:%S"),
                "FINISHED":0,
            }
        setup['STATS'].update(self.param)

        self.scenario.sim_report = json.dumps(setup)
        self.scenario.save()


        # RUN SCENARIOS 
        if RUN_ENV == 'celery':
            print("RUNNING IN CELERY")
            task = celery.send_task('optimize_simulate',args=[self.scenario.id, self.param, "Simulator", True, self.param['RUNMODE'], int(self.param['LOCALSEARCHTIME'])])
            self.scenario.task_id = task.id
            self.scenario.stopComputation = False
            self.scenario.save()
        else:
            optimize_simulate(self.scenario.id, self.param, "Simulator", True, runMode=self.param['RUNMODE'], localsearch_time=int(self.param['LOCALSEARCHTIME']))


    def improve(self):

        # IMPROVE ALL SCENARIOS SCENARIOS 

        scenarios = []
        if self.scenario.sim_report:            
            kpis = json.loads(self.scenario.sim_report)            
            for kpi in kpis:
                if kpi.isnumeric() and Scenario.objects.filter(id=kpi).exists():
                    scenarios.append(kpi)




        if RUN_ENV == 'celery':
            task = celery.send_task('optimize_sequentially',args=[scenarios, "Simulator", True, self.param['RUNMODE'], int(self.param['LOCALSEARCHTIME'])])
            self.scenario.task_id = task.id
            self.scenario.stopComputation = False
            self.scenario.save()
        else:
            optimize_sequentially(scenarios, user_name="Simulator", user_is_staff=True, runMode=self.param['RUNMODE'], localsearch_time=int(self.param['LOCALSEARCHTIME']))
