function addGridAxesToolbar(ax)
%ADDGRIDAXESTOOLBAR Add a cusotmized toolbar to the axes in the Econometri
%Modeler app

%Copyright 2019 The MathWorks, Inc.

%Create initial toolbar with standard zoom, pan, and restore buttons
tb = axtoolbar(ax,{'zoomin','zoomout','pan','restoreview'},'Tag','econModelerAxesToolbar');

%Create legend button
legendBtn = axtoolbarbtn(tb,'state','Tag','legendButton');
legendBtn.Tooltip = getString(message('econ:econModeler:Legend'));
legendBtn.Icon = internal.EconModeler.getIconSource('Legend_16');
legendBtn.ValueChangedFcn = @(e, d) localToggleLegend(e,d);

%Initial value depends on whether a legend is visible
if isempty(ax.Legend)
    legendBtn.Value = 'off';
else
    legendBtn.Value = 'on';
end

%Create grid button
gridBtn = axtoolbarbtn(tb,'state','Tag','gridButton');
gridBtn.Tooltip = getString(message('econ:econModeler:Grid'));
gridBtn.Icon = internal.EconModeler.getIconSource('FloatingPalleteGrid_default_16');
gridBtn.ValueChangedFcn = @(e, d) localToggleGrid(e,d);

%Initial value based on whether a grid is visible
if ax.XGrid == "on" && ax.YGrid == "on"
    gridBtn.Value = 'on';
else
    gridBtn.Value = 'off';
end

function localToggleLegend(source, eventData)
%Turn legend on or off
if strcmpi(source.Value, 'on')
    legend(eventData.Axes, 'show');
else
    legend(eventData.Axes, 'off');
end
end

function localToggleGrid(source, eventData)
%Turn grid on or off
if strcmpi(source.Value, 'on')
    grid(eventData.Axes, 'on');
else
    grid(eventData.Axes, 'off');
end
end

end

