function varargout = sf_rf24mesh_init_cb(varargin)
% sf_rf24mesh_init_cb
    
% Copyright 2015 - 2016 The MathWorks, Inc.

    if nargout == 0
        feval(varargin{:});
    else
        [varargout{1:nargout}] = feval(varargin{:});
    end
end

function [dstr, isMaster] = init(blk) %#ok<DEFNU>
    setNetworkChannel = strcmp('on', get_param(blk, 'pChooseNetworkChannel'));
    if setNetworkChannel
        nwStr = sprintf('Channel: #%s', get_param(blk, 'pNetworkChannel'));
    else
        nwStr = 'Channel: <default>';
    end

    dstr=sprintf('RF24Mesh Init\nNode: %s\n%s', get_param(gcb, 'pMeshNode'), nwStr);
    outputInfo = strcmp(get_param(blk, 'pOutMeshInfo'), 'on');
    if outputInfo
        dstr = sprintf('%s\nOutput Info', dstr);
    end
    isMaster = nodeIsMaster(blk);
end

function ret = nodeIsMaster(blk)
    nID = get_param(blk, 'pMeshNode');
    id = str2double(nID);
    ret = id == 0;
end

function check_master_node(blk) %#ok<DEFNU>
    isMaster = nodeIsMaster(blk);
    idcs = [...
        getIdxForName(blk, 'pOutMeshInfo'), ...
        getIdxForName(blk, 'pMeshInfoTS') ...
        ];
    me = get_param(blk, 'MaskEnables');
    idx = getIdxForName(blk, 'pAPIKEY');
    if ~isempty(idx)
        idcs(end+1) = idx;
    end
    setEnables = false;
    if isMaster
        % Master node
        if strcmp(me{idcs(1)}, 'off')
            for k=1:length(idcs)
                me{idcs(k)} = 'on';
            end
            setEnables = true;
        end
    else
        % Not master node
        if strcmp(me{idcs(1)}, 'on')
            for k=1:length(idcs)
                me{idcs(k)} = 'off';
            end
            setEnables = true;
        end
    end
    if setEnables
        set_param(blk, 'MaskEnables', me);
    end
end

function choose_network_ch(blk) %#ok<DEFNU>
    setNetworkChannel = strcmp('on', get_param(blk, 'pChooseNetworkChannel'));
    idx = getIdxForName(blk, 'pNetworkChannel');
    enabs = get_param(blk, 'MaskEnables');
    if setNetworkChannel
        if strcmp('off', enabs{idx});
            enabs{idx} = 'on';
            set_param(blk, 'MaskEnables', enabs);
        end
    else
        if strcmp('on', enabs{idx});
            enabs{idx} = 'off';
            set_param(blk, 'MaskEnables', enabs);
        end        
    end
    
end

function idx = getIdxForName(blk, name)
   names = get_param(blk, 'MaskNames');
   idx = find(strcmp(name, names), 1);
end