const system = {
    _pendingRequests: new Map(),
    _listeners: new Map(),

    init: function() {
        window.external.receiveMessage(response => {
            try {
                const res = JSON.parse(response)
                if (res.requestId && this._pendingRequests.has(res.requestId)) {
                    const { resolve } = this._pendingRequests.get(res.requestId);
                    this._pendingRequests.delete(res.requestId);
                    resolve(res.payload);
                }
                else if (res.requestId && this._listeners.has(res.requestId)) {
                    const callback = this._listeners.get(res.requestId);
                    callback(res.payload);
                }
            } catch (e) {
                console.error("Erreur format message :", e)
            }
        })
    },

    call: function(functionName, data = {}) {
        return new Promise((resolve, reject) => {
            const requestId = Math.random().toString(36).substring(7)
            
            this._pendingRequests.set(requestId, { resolve, reject })

            window.external.sendMessage(JSON.stringify({
                requestId: requestId,
                functionName: functionName,
                payload: data
            }))
        })
    },

    result: function(eventName, callback) {
        this._listeners.set(eventName, callback);
    }
}

window.external.receiveMessage(message => {
    try {
        const data = JSON.parse(message)
        
        switch (data.requestId) {
            case "game::log":
                const logMessage = data.payload.message
                if (logMessage != "GAME_CLOSED") {                    
                    console.log("MC:", logMessage)
                    gamelog.put(logMessage)
                    logsContainer.scrollTop = logsContainer.scrollHeight
                } else {
                    playButton.removeAttribute("disabled")
                }
                break;
        
            default:
                break;
        }
    } catch (e) {
        console.error("Erreur réception message Photino:", e)
    }
})

system.init()