# -*- coding: utf-8 -*-
import ecole
import pyscipopt
from pyscipopt import scip


def set_params(pyscipopt_model: pyscipopt.Model, static_params={}, dynamic_params={}):
    # pyscipopt_model.setPresolve(scip.PY_SCIP_PARAMSETTING.OFF)  # keep presolve
    # pyscipopt_model.setSeparating(scip.PY_SCIP_PARAMSETTING.ON)  # activate cutting planes
    # pyscipopt_model.setParam("heuristics/feaspump/freq", 20)  # enable feas pump
    pyscipopt_model.setHeuristics(scip.PY_SCIP_PARAMSETTING.DEFAULT)  # activate heuristics
    pyscipopt_model.setParam("separating/maxrounds", 0)  # activate cutting planes only at root node
    if "cutfree" in static_params and static_params["cutfree"]:
        pyscipopt_model.setParam("separating/maxroundsroot", 0)
    pyscipopt_model.setParam("estimation/restarts/restartpolicy", "n")  # disable restarts
    pyscipopt_model.setParam("limits/time", 3600)  # time limit
    if "donot_feaspump" in static_params and static_params["donot_feaspump"] is True:
        pyscipopt_model.setParam("heuristics/feaspump/freq", -1)
    if "branching_rule" in static_params and static_params["branching_rule"] is not None:
        pyscipopt_model.setParam(f"branching/{static_params['branching_rule']}/priority", 10001)
        if static_params["branching_rule"] == "vanillafullstrong":
            # voir si on enleve ça dans certain cas
            pyscipopt_model.setParam("branching/vanillafullstrong/idempotent", True)
    if "node_selection" in static_params and static_params["node_selection"] is not None:
        pyscipopt_model.setParam(f"nodeselection/{static_params['node_selection']}/stdpriority", 300000)
        pyscipopt_model.setParam(f"nodeselection/{static_params['node_selection']}/memsavepriority", 300000)
    if "node_limit" in static_params and static_params["node_limit"] is not None:
        pyscipopt_model.setParam("limits/nodes", static_params["node_limit"])
    if "time_limit" in static_params and static_params["time_limit"] is not None:
        pyscipopt_model.setParam("limits/time", static_params["time_limit"])


class ConfiguringDynamics(ecole.dynamics.ConfiguringDynamics):
    def __init__(self, static_params={}):
        super().__init__()
        self.static_params = static_params

    def reset_dynamics(self, model, dynamic_params={}):
        set_params(model.as_pyscipopt(), self.static_params, dynamic_params)
        return super().reset_dynamics(model)


class BranchingDynamics(ecole.dynamics.BranchingDynamics):
    def __init__(self, static_params={}):
        super().__init__()
        self.static_params = static_params

    def reset_dynamics(self, model, dynamic_params={}):
        set_params(model.as_pyscipopt(), self.static_params, dynamic_params)
        return super().reset_dynamics(model)


class Configuring(ecole.environment.Environment):
    __Dynamics__ = ConfiguringDynamics


class Branching(ecole.environment.Environment):
    __Dynamics__ = BranchingDynamics
