package com.tibbo.aggregate.common.expression.function.datablock;

import java.text.MessageFormat;
import java.util.Arrays;

import com.tibbo.aggregate.common.Cres;
import com.tibbo.aggregate.common.data.Data;
import com.tibbo.aggregate.common.expression.EvaluationEnvironment;
import com.tibbo.aggregate.common.expression.EvaluationException;
import com.tibbo.aggregate.common.expression.Evaluator;
import com.tibbo.aggregate.common.expression.Function;
import com.tibbo.aggregate.common.expression.function.AbstractFunction;

public class BytesFunction extends AbstractFunction
{
  public BytesFunction()
  {
    super("bytes", Function.GROUP_DATA_BLOCK_PROCESSING, "DataBlock data, Integer beginIndex [, Integer endIndex]", "DataBlock", Cres.get().getString("fDescBytes"));
    
  }
  
  @Override
  public Object execute(Evaluator evaluator, EvaluationEnvironment environment, Object... parameters) throws EvaluationException
  {
    checkParameters(2, false, parameters);
    Data dataBlock = (Data) parameters[0];
    int beginIndex = ((Number) parameters[1]).intValue();
    if (beginIndex >= dataBlock.getData().length || beginIndex < 0)
    {
      throw new EvaluationException(MessageFormat.format(Cres.get().getString("fErrOutOfBound"), beginIndex));
    }
    
    if (parameters.length == 2)
    {
      return new Data(Arrays.copyOfRange(dataBlock.getData(), beginIndex, dataBlock.getData().length));
    }
    else
    {
      int endIndex = ((Number) parameters[2]).intValue();
      if (endIndex > dataBlock.getData().length || endIndex < 0)
      {
        throw new EvaluationException(MessageFormat.format(Cres.get().getString("fErrOutOfBound"), endIndex));
      }
      return new Data(Arrays.copyOfRange(dataBlock.getData(), beginIndex, endIndex));
    }
  }
}
