/*

Siesta 5.6.1
Copyright(c) 2009-2022 Bryntum AB
https://bryntum.com/contact
https://bryntum.com/products/siesta/license

*/
Singleton('Siesta.Project.Browser.Automation.ScriptExecutor', {
    
    has : {
        currentScriptExecution          : null
    },
    
    
    methods : {
        
        // trying to prevent any possibility of the mess with the script
        acceptScriptChunk : function (scriptId, maxMessageSize, chunk, index, isLast) {
            var currentScriptExecution      = this.currentScriptExecution
            
            if (currentScriptExecution) {
                if (currentScriptExecution.id != scriptId) throw new Error("Another execution in progress")
                if (currentScriptExecution.maxMessageSize != maxMessageSize) throw new Error("`maxMessageSize` has changed")
            } else {
                if (index) throw new Error("Starting from non-zero chunk")
                
                this.currentScriptExecution = currentScriptExecution = new Siesta.Project.Browser.Automation.ScriptExecution({
                    id              : scriptId,
                    maxMessageSize  : maxMessageSize
                })
            }
            
            currentScriptExecution.addChunk(chunk, index)
            
            if (isLast) {
                currentScriptExecution.execute()
                return this.retrieveScriptResult(scriptId, 0)
            } else {
                return "Chunk received successfully"
            }
        },
        
        
        retrieveScriptResult : function (scriptId, index) {
            var currentScriptExecution      = this.currentScriptExecution
            
            if (!currentScriptExecution) throw new Error("No current script execution")
                
            var res         = currentScriptExecution.getPartialResult(scriptId, index)
            
            if (currentScriptExecution.isDestroyed) this.currentScriptExecution = null
            
            return res
        }
    }
})