package cz.martinstainer.sampler;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.regex.Matcher;

import cz.martinstainer.helper.TPerfResultGetter;

import org.apache.jmeter.config.Argument;
import org.apache.jmeter.config.Arguments;
import org.apache.jmeter.samplers.AbstractSampler;
import org.apache.jmeter.samplers.Entry;
import org.apache.jmeter.samplers.SampleResult;
import org.apache.jmeter.services.FileServer;
import org.apache.jmeter.testelement.property.TestElementProperty;
import org.apache.jorphan.exec.SystemCommand;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import cz.martinstainer.helper.IPerfResultGetter;

public class TPerfSampler extends AbstractSampler {

    private static final long serialVersionUID = 240L;

    public static final String ARGUMENTS = "TPerfSampler.arguments";

    private static final Logger log = LoggerFactory.getLogger(TPerfSampler.class);

    // The name of the property used to hold our data
    public static final String DATA = "TPerf.data"; //$NON-NLS-1$

    private static AtomicInteger classCount = new AtomicInteger(0); // keep track of classes created

    // (for instructional purposes only!)

    public TPerfSampler() {
        classCount.incrementAndGet();
        trace("TPerfSampler()");
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public SampleResult sample(Entry e) {
        trace("sample()");

        SampleResult sampleResults = new SampleResult();
        sampleResults.setContentType("tperf");
        String data = getData(); // Sampler data
        sampleResults.setSampleLabel(getTitle());
        String command = "./tperf";
        ArrayList<String> cmds = new ArrayList<String>(1);
        cmds.add(command);
            SystemCommand nativeCommand = null;
        File directory = new File("/home/x/Projects/mvfst/_build/build/quic/tools/tperf/");

        Arguments args = getArguments();
        for (int i=0; i < args.getArgumentCount(); i++) {
            Argument arg = args.getArgument(i);
            cmds.add(arg.getPropertyAsString(Argument.VALUE));
        }
        try {
            if(log.isDebugEnabled()) {
                log.debug("Running tperf");
            }
            nativeCommand = new SystemCommand(directory, null);
            sampleResults.sampleStart();
            int returnCode = nativeCommand.run(cmds);
            sampleResults.sampleEnd();
            sampleResults.setResponseCode(Integer.toString(returnCode));
            sampleResults.setLatency(1);
            sampleResults.setResponseData(nativeCommand.getOutResult());
            Matcher matcher = TPerfResultGetter.get(nativeCommand.getOutResult());
            SampleResult sr = new SampleResult();
            while(matcher.find()) {
                float number = Float.parseFloat(matcher.group().substring(0, 4));
                sr.setSentBytes((long) (number * 1024.0));
                break;
            }
            sampleResults.setBytes(sr.getSentBytes());
            sampleResults.setSentBytes(sr.getSentBytes());
            if ((returnCode != 0)) {
                sampleResults.setSuccessful(false);
                sampleResults.setResponseMessage("Unexpected return code.  Expected ["+ 1 +"]. Actual ["+returnCode+"].");
            } else {
                sampleResults.setSuccessful(true);
                sampleResults.setResponseMessage("OK");
            }
        } catch (IOException ioe) {
            sampleResults.sampleEnd();
            sampleResults.setSuccessful(false);
            sampleResults.setResponseCode("500"); //$NON-NLS-1$
            sampleResults.setResponseMessage("Exception occurred whilst executing system call: " + ioe);
        } catch (InterruptedException ie) {
            sampleResults.sampleEnd();
            sampleResults.setSuccessful(false);
            sampleResults.setResponseCode("500"); //$NON-NLS-1$
            sampleResults.setResponseMessage("System Sampler interrupted whilst executing system call: " + ie);
            Thread.currentThread().interrupt();
        } catch (TimeoutException ee) {
            sampleResults.sampleEnd();
            sampleResults.setSuccessful(false);
            sampleResults.setResponseCode("500");
            sampleResults.setResponseMessage(ee.getMessage());
        }
        return sampleResults;
    }


    public Arguments getArguments() {
        return (Arguments) getProperty(ARGUMENTS).getObjectValue();
    }

    /**
     * @return a string for the sampleResult Title
     */
    private String getTitle() {
        return this.getName();
    }

    /**
     * @return the data for the sample
     */
    public String getData() {
        return getPropertyAsString(DATA);
    }

    public String getName() {
        return "TPerf Sampler";
    }

    public void setArguments(Arguments args) {
        setProperty(new TestElementProperty(ARGUMENTS, args));
    }

    /*
     * Helper method
     */
    private void trace(String s) {
        if (log.isDebugEnabled()) {
            log.debug("{} ({}) {} {} {}", Thread.currentThread().getName(), Integer.valueOf(classCount.get()),
                    getTitle(), s, this.toString());
        }
    }
}
