% ByteBufferItemWrapper - An RAII MATLAB wrapper for a Java ByteBufferItem

% Copyright 2015 The MathWorks, Inc.

classdef ByteBufferItemWrapper < handle
    properties (Access = private)
        ByteBufferItem
        JavaValue
        SerializedValue = []
    end

    methods (Static)
        function wrapper = wrapInByteBufferItem(val)
            s = distcompserialize64(val);
            [item, v] = iWrapNoSerialization(s);
            wrapper = parallel.internal.cluster.ByteBufferItemWrapper(item, v, s);
        end

        function wrapper = wrapInByteBufferItemNoSerialization(val)
            [item, v] = iWrapNoSerialization(val);
            wrapper = parallel.internal.cluster.ByteBufferItemWrapper(item, v);
        end
    end

    methods
        function val = get(obj)
            val = obj.JavaValue;
        end

        function delete(obj)
            if ~isempty(obj.ByteBufferItem)
                obj.ByteBufferItem.delete();
            end
        end
    end

    methods (Access = private)
        function val = ByteBufferItemWrapper(byteBufferItem, javaValue, serializedValue)
            val.ByteBufferItem = byteBufferItem;
            val.JavaValue = javaValue;
            if nargin >= 3
                val.SerializedValue = serializedValue;
            end
        end
    end
end

function [item, v] = iWrapNoSerialization(val)
    import com.mathworks.toolbox.distcomp.mjs.datastore.ByteBufferItem

    item = ByteBufferItem(distcompWrapInByteBufferHandles(val));
    v = dctJavaArray(item, ...
            'com.mathworks.toolbox.distcomp.mjs.datastore.LargeData');
end
