package com.eactive.eai.transformer.function.generic;

import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.util.Stack;

import org.nfunk.jep.ParseException;
import org.nfunk.jep.function.PostfixMathCommand;

public class DoubleToBytes extends PostfixMathCommand {
    public DoubleToBytes() {
        numberOfParameters = 1;
    }
    
//  Double 형 Binary(8Bytes) 를 Byte 문자 로
    public void run(Stack inStack) throws ParseException {
    	checkStack(inStack);

        Object p1 = inStack.pop();
        

        if (p1 instanceof byte[]) {
            byte[] bytes = (byte[]) p1;

            if (bytes.length != 8)
            	throw new ParseException("'DoubleToBytes' function argument must be 8 bytes binary");
            
            final int size = Double.SIZE / 8;
    	    ByteBuffer buff = ByteBuffer.allocate(size);
    	    final byte[] newBytes = new byte[size];
    	    for (int i = 0; i < size; i++) {
    	    	if (i + bytes.length < size) {            
    	    		newBytes[i] = (byte) 0x00;
    	        } 
    	        else {
    	        	newBytes[i] = bytes[i + bytes.length - size];
    	        }
    		}
    		buff = ByteBuffer.wrap(newBytes);
    		buff.order(ByteOrder.BIG_ENDIAN);
    	    
            inStack.push(new Double(buff.getDouble()));        
        } else {
            throw new ParseException("Invalid parameter type");
        }        
    }
}
