package ex2;

import ch.usi.dag.disl.annotation.After;
import ch.usi.dag.disl.annotation.Before;
import ch.usi.dag.disl.annotation.ThreadLocal;
import ch.usi.dag.disl.dynamiccontext.DynamicContext;
import ch.usi.dag.disl.marker.BodyMarker;
import ch.usi.dag.disl.marker.BytecodeMarker;

public class Instrumentation {

    @ThreadLocal
    static long readCount;

    @ThreadLocal
    static long writeCount;

    @Before(marker = BytecodeMarker.class, args = "getfield")
    static void beforeGetField() {
        readCount++;
    }

    @Before(marker = BytecodeMarker.class, args = "putfield")
    static void beforePutField() {
        writeCount++;
    }

    @After(marker = BodyMarker.class,
            scope = "void run()",
            guard = IsTriviallyThreadGuard.class)
    static void onThreadExit() {
        Profiler.increment(readCount, writeCount);
    }

    @After(marker = BodyMarker.class,
            scope = "void run()",
            guard = IsNotTriviallyThreadGuard.class)
    static void onThreadExit(final DynamicContext dc) {
        if (Profiler.isThread(dc.getThis().getClass())) {
            Profiler.increment(readCount, writeCount);
        }
    }
}
