package com.eactive.eai.adapter.socket2.protocol;

import java.io.BufferedReader;
import java.io.FileReader;

import com.eactive.eai.adapter.socket2.config.SocketLoggerManager;
import com.eactive.eai.common.util.Logger;

import groovy.lang.Binding;
import groovy.lang.GroovyShell;

public class Groovy {
	String filename;
	String adapterName;
	protected final Logger logger;
	public Groovy(String filename, String adapterName) {
		this.filename = filename;
		this.adapterName = adapterName;
		logger = SocketLoggerManager.getInstance().getLogger();
	}
	
  	public byte[] run(byte[] request) throws Exception {
		Binding binding = new Binding();
		binding.setVariable("adapterName", adapterName);
		binding.setVariable("request", request);		
		binding.setVariable("response", request);		
		GroovyShell shell = new GroovyShell(binding);
		StringBuilder sb = new StringBuilder();
		try (
			FileReader fr = new FileReader(filename);
			BufferedReader br = new BufferedReader(fr);
		){
			String line = "";		
			while ((line = br.readLine()) != null) {	
				sb.append(line + "\n");
			}
		}
		catch(Exception e) {
			logger.debug(e.toString());
		}
	    shell.evaluate(sb.toString());
	    return (byte[]) binding.getVariable("response");
  	}
}

