package org.globus.progtutorial.services.core.core_sd.impl;


import org.codehaus.aspectwerkz.xmldef.advice.AroundAdvice;
import org.codehaus.aspectwerkz.joinpoint.JoinPoint;
import org.codehaus.aspectwerkz.joinpoint.MethodJoinPoint;
import org.globus.progtutorial.stubs.MathService_sd_notif.MathPortType;
import org.globus.progtutorial.stubs.MathService_sd_notif.servicedata.MathDataType;
import org.globus.ogsa.GridServiceBase;
import org.globus.ogsa.ServiceData;
import org.gridforum.ogsi.TargetInvalidFaultType;
import org.gridforum.ogsi.ExtensibilityType;
import org.gridforum.ogsi.HandleType;
import javax.xml.namespace.QName;

import org.codehaus.aspectwerkz.*;
import org.codehaus.aspectwerkz.xmldef.introduction.*;

public class ServiceDataAspect extends AroundAdvice
{
    private GridServiceBase base;
    private ServiceData mathDataSDE;
    private MathDataType mathDataValue;

   

    public ServiceDataAspect(){
        super();
    }



    public Object execute(final JoinPoint joinPoint) throws Throwable {
        MethodJoinPoint jp = (MethodJoinPoint)joinPoint;
        final Object result = joinPoint.proceed();

        if(jp.getMethodName().compareTo("preCreate")==0){

            base = (GridServiceBase)(jp.getParameters()[0]);
            mathDataSDE = base.getServiceDataSet().create("MathData");

            // Create a MathDataType instance and set intial values
            mathDataValue = new MathDataType();
            mathDataValue.setLastOp("NONE");
            mathDataValue.setNumOps(0);
            mathDataValue.setValue(0);

            // Set the value of the SDE to the MathDataType instance
            mathDataSDE.setValue(mathDataValue);

            // Add SDE to Service Data Set
            base.getServiceDataSet().add(mathDataSDE);
        }
        else
        {
            mathDataValue.setLastOp(jp.getMethodName());
            incrementOps();
            mathDataValue.setValue(((MathService)jp.getTargetInstance()).getValue());
        }


        return result;
    }


    private void incrementOps(){
        int numOps = mathDataValue.getNumOps();
        mathDataValue.setNumOps(numOps + 1);
    }
}