import RAFT from "@robotical/webapp-types/dist-types/src/application/RAFTs/RAFT";

export const raftPubSubscriptionHelper = (raft: RAFT) => {
    let observer: { notify: (eventType: string, eventEnum: any, eventName: string, eventData: any) => void } | null = null;
    return {
        subscribe: (callback: (eventData: any) => void) => {
            observer = raftPubSubscriptionObserver_(callback);
            raft.subscribe(observer, ["raftinfo"])
        },
        unsubscribe: () => {
            if (observer) {
                raft.unsubscribe(observer);
            }
        }
    };
}

const raftPubSubscriptionObserver_ = (callback: (eventData: any) => void) => {
    return {
        notify(
            eventType: string,
            eventEnum: any,
            eventName: string,
            eventData: any
        ) {
            switch (eventType) {
                case "raftinfo":
                    switch (eventEnum) {
                        case "STATE_INFO":
                            callback(eventData);
                            break;
                        default:
                            break;
                    }
                    break;
            }
        },
    };
};


/** 
 * RAFT Disconnected Subscription Helper
 */
export const raftDisconnectedSubscriptionHelper = (raft: RAFT) => {
    let observer: { notify: (eventType: string, eventEnum: any, eventName: string, eventData: any) => void } | null = null;
    return {
        subscribe: (callback: any) => {
            observer = raftDisconnectedSubscriptionObserver_(callback);
            raft.subscribe(observer, ["conn"]);
        },
        unsubscribe: () => {
            if (observer) {
                raft.unsubscribe(observer);
            }
        }
    }
}

const raftDisconnectedSubscriptionObserver_ = (callback: any) => {
    return {
        notify(
            eventType: string,
            eventEnum: any,
            eventName: string,
            eventData: any
        ) {
            switch (eventType) {
                case "conn":
                    switch (eventEnum) {
                        case 3:
                            callback();
                            break;
                        default:
                            break;
                    }
                    break;
            }
        },
    };
};