function out = dcfNodeInfo(opType, nodeID)
% dcfNodeInfo Performs get or set operation for MAC address of the given
% node
%
%   OUT = dcfNodeInfo(OPTYPE, NODEID) performs the operation specified
%   by the OPTYPE on the node with the given NODEID. If the OPTYPE is
%   specified as 0, a random MAC address is assigned to the node with the
%   specified NODEID and the same address is returned as the output OUT. If
%   the OPTYPE is specified as 1, the MAC address for the node with the
%   given NODEID is returned as the output OUT.
%
%   OUT is the output MAC address, returned as a 6-element integer row
%   vector representing octets in decimal format.
%
%   OPTYPE is the operation to be performed, specified as 0 or 1. The value
%   0 indicates 'assign' operation and the value 1 indicates 'retrieve'
%   operation.
%
%   NODEID is the ID of the node specified by the user.

%   Copyright 2019 The MathWorks, Inc.

% Holds each node information(i.e., node id and MAC address) in the simulation .
persistent nodeInfo;
% Keep the count of number of nodes in the simulation.
persistent nodeIdCounter;
% Initialize nodeInfo structure.
if isempty(nodeInfo)
    s.id = 0;
    s.macAddr = [0 0 0 0 0 0];
    % Maximum number of nodes creation in a model is restricted to 250. Any
    % changes to maxNumberOfNodes variable value needs to be carried to the
    % maxNumberOfNodes variable in the dcfUpdateStats function.
    maxNumberOfNodes = 250;
    nodeInfo = repmat(s, maxNumberOfNodes, 1);
end
% Initialize nodeIdCount to zero.
if isempty(nodeIdCounter)
    nodeIdCounter = 0;
end
% Assign default value to output variable.
out = [0 0 0 0 0 0];

% Switch to an operation type that is selected.
switch(opType)
    case 0
        % If MAC address of a node is all zeros, Assign unique MAC address
        % to it. Otherwise, returns already assigned MAC address.
        if nodeInfo(nodeID).id == 0
            % Increment nodeIdCounter by 1.
            nodeIdCounter = nodeIdCounter +1;
            % Store nodeId in nodeInfo array.
            nodeInfo(nodeID).id = nodeID;
            % Generate a random MAC address and store it in nodeInfo array.
            nodeInfo(nodeID).macAddr = hex2dec(reshape(dec2hex(nodeID, 12), 2, 6)')';
        end
        out = nodeInfo(nodeID).macAddr;
    case 1
        % Find and return MAC address of a node using nodeId.
        if (nodeID <= nodeIdCounter) && (nodeID > 0)
            out = nodeInfo(nodeID).macAddr;
        elseif nodeID == 255
            out = [255 255 255 255 255 255];
        else
            out = [0 0 0 0 0 0];
        end
    case 2
        % Returns the number of nodes in the simulation.
        out = [nodeIdCounter 0 0 0 0 0];
end