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

state_mapping = {
    "IDLE": RegistrationForm.RegistrationFormStatus.RF_IDLE, 
    "INITIALIZED": RegistrationForm.RegistrationFormStatus.RF_INITIALIZED,
    "SENT": RegistrationForm.RegistrationFormStatus.RF_SENT,
    "UNDER_REVIEW": RegistrationForm.RegistrationFormStatus.RF_UNDER_REVIEW,
    "TO_BE_FOLLOWED_UP": RegistrationForm.RegistrationFormStatus.RF_TO_BE_FOLLOWED_UP,
    "VALIDATED": RegistrationForm.RegistrationFormStatus.RF_VALIDATED,
    "ARCHIVED": RegistrationForm.RegistrationFormStatus.RF_ARCHIVED,
    "SEPA_SENT": RegistrationForm.RegistrationFormStatus.RF_SEPA_SENT,
    "SEPA_TO_SEND": RegistrationForm.RegistrationFormStatus.RF_SEPA_TO_SEND
}

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)
    if state_machine.trigger(transition, automateModel):
        rf.status = state_machine.state
        rf.save()

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