const system = {
    _pendingRequests: 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)
                }
            } 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
            }))
        })
    }
}

system.init()