# state_machine.py
import json
from Subscriptions.models import RegistrationForm
from Subscriptions.signals import clear_cache

state_mapping = {
    "ABSENT": RegistrationForm.RegistrationFormStatus.RF_ABSENT, 
    "CREE": RegistrationForm.RegistrationFormStatus.RF_CREATED,
    "ENVOYE": RegistrationForm.RegistrationFormStatus.RF_SENT,
    "EN_VALIDATION": RegistrationForm.RegistrationFormStatus.RF_UNDER_REVIEW,
    "A_RELANCER": RegistrationForm.RegistrationFormStatus.RF_TO_BE_FOLLOWED_UP,
    "VALIDE": RegistrationForm.RegistrationFormStatus.RF_VALIDATED,
    "ARCHIVE": RegistrationForm.RegistrationFormStatus.RF_ARCHIVED
}

def load_config(config_file): 
    with open(config_file, 'r') as file: 
        config = json.load(file) 
        return config

def getStateMachineObject(etat) :
    return Automate_RF_Register(etat)

def getStateMachineObjectState(etat):
    return Automate_RF_Register(etat).state

def updateStateMachine(rf, transition) :
    automateModel = load_config('Subscriptions/Configuration/automate.json')
    state_machine = getStateMachineObject(rf.status)
    print(f'etat DI : {state_machine.state}')
    if state_machine.trigger(transition, automateModel):
        rf.status = state_machine.state
        rf.save()
        clear_cache()

class Automate_RF_Register:
    def __init__(self, initial_state):
        self.state = initial_state

    def trigger(self, transition_name, config):
        for transition in config["transitions"]:
            if transition["name"] == transition_name and self.state == state_mapping[transition["from"]]:
                self.state = state_mapping[transition["to"]]
                return True
        return False