package com.hobsonslabs.hadoop;

import io.netty.buffer.DrillBuf;
import org.apache.drill.exec.expr.DrillSimpleFunc;
import org.apache.drill.exec.expr.annotations.FunctionTemplate;
import org.apache.drill.exec.expr.annotations.Output;
import org.apache.drill.exec.expr.annotations.Param;
import org.apache.drill.exec.expr.annotations.Workspace;
import org.apache.drill.exec.expr.holders.NullableVarCharHolder;
import org.apache.drill.exec.expr.holders.VarCharHolder;

import javax.inject.Inject;

@FunctionTemplate(
    name = "to_md5",
    scope = FunctionTemplate.FunctionScope.SIMPLE,
    nulls = FunctionTemplate.NullHandling.NULL_IF_NULL
)

public class MD5MaskFunc implements DrillSimpleFunc {

    @Param
    NullableVarCharHolder input;

    @Output
    VarCharHolder out;

    @Inject
    DrillBuf buffer;

    @Workspace
    com.google.common.hash.HashFunction hashFunction;

    public void setup() {
        hashFunction = com.google.common.hash.Hashing.md5();
    }

    public void eval() {

        String stringValue = org.apache.drill.exec.expr.fn.impl.StringFunctionHelpers.toStringFromUTF8(
            input.start, input.end, input.buffer );

        com.google.common.hash.HashCode hashCode = hashFunction.hashString(stringValue, java.nio.charset.StandardCharsets.UTF_8);

        String outputValue = hashCode.toString();

        // put the output value in the out buffer
        out.buffer = buffer;
        out.start = 0;
        out.end = outputValue.getBytes().length;
        buffer.setBytes(0, outputValue.getBytes());
    }

}