function insertAxes(fig, value)
% INSERTAXES Helper function for the figure toolstrip

% Copyright 2020 The MathWorks, Inc.

% Disable the gca listener when inserting the axes layout
if isprop(fig,'MOLToolstripAxesListener')
    fig.MOLToolstripAxesListener.Enabled = false;
end

try 
    allAxes = findall(fig, 'Type', 'axes');        
    
    hasChildren = zeros(numel(allAxes), 1);
    for i=1:numel(allAxes)
        hasChildren(i) = ~isempty(get(allAxes(i), 'Children'));
    end
    
    % We only need to reparent the ones with proper children
    allAxes = allAxes(hasChildren == 1);
    
    lastAxesPositions = get(allAxes,{'Position'});
    localInsertAxes(fig, allAxes, value)

    % Add to Undo/redo stack
    cmd.Name = ['add axes'];
    cmd.Function = @(fig,~) localInsertAxes(fig, allAxes, value);
    cmd.InverseFunction  = @(fig,~) localInverse(fig, allAxes, lastAxesPositions);
    cmd.Varargin = {fig};
    cmd.InverseVarargin = {fig};
    uiundo(fig,'function',cmd); 
catch
end

% Re-enable the gca listener
if isprop(fig,'MOLToolstripAxesListener')
    fig.MOLToolstripAxesListener.Enabled = true;
end

end

function localInverse(fig, lastAxes, lastAxesPositions)
    % Create the inverse function for the axes insert 
	% for undo/redo stack
	tiledLayout = fig.Children;
    set(lastAxes, 'Parent', []);
    delete(tiledLayout);
    
    for k=1:numel(lastAxes)
        lastAxes(k).Position = lastAxesPositions{k};
    end
    lastAxes.Parent = fig;
end

function localInsertAxes(fig, allAxes, value)
    
    % Unparent the colorbars
    colorbars = findobj(fig, 'type', 'colorbar');
    set(colorbars, 'Parent', []);
    
    % Unparent all the existing axes 
    set(allAxes, 'Parent', []);   
    
    % Unparent any legends
    l = findobj(fig, 'type', 'legend');   
    set(l, 'Parent', []);                
    
    % Clean out the old layout objects
    delete(findobj(fig, 'type', 'tiledlayout'));   
    
    % If I'm selecting a 1x1 grid, use the flow layout option
    % else build the grid
    if value.row == 1 && value.column == 1        
        t = tiledlayout(fig, 'flow');
    else
        % Put the existing axes in the new layout
        t = tiledlayout(fig, value.row, value.column);
    end
    
    % First set the axes new parent as the tiledlayout
    set(allAxes, 'Parent', t);    
    
    lastTile = 1;
    
    % For each axes, put it in the right tile
    for i=1:numel(allAxes)
        ax = allAxes(i);
        ax.Layout.Tile = i;
        
        % If my existing axes came with a legend, reparent it
        if ~isempty(ax.Legend)
            set(ax.Legend, 'Parent', t);
        end
        
        for j=1:numel(colorbars)
            cBar = colorbars(j);
            
            % Re-create the colorbar if needed
            if isequal(cBar.Axes, ax)                
                colorbar(ax);
            end
        end
        
        lastTile = i;
    end
    
    numTiles = value.row * value.column;
    % Fill in the remaining tiles with empty axes
    for i=lastTile:numTiles
        nexttile(i);
    end
end