% Author: Matthew Dawson matthew@mjdsystems.ca
% Organization: McMaster Centre for Software Certification

function [] = add_cell( object, beneath_cell, after_cell )
%% ADD_CELL Add a cell to the grid.
%   Adds a new cell to the grid, updates relevant information throughout,
%   and sends appropriate update signals.

    %% Find Subgrid
    if isempty(beneath_cell)
        subgrid = object;
    else 
        subgrid = beneath_cell;
    end
    
    NewCell = HierarchicalGridCell();
        
    if isempty(after_cell)
        %% Append cell to grid
        % Append the cell to the current grid.
        
        % Find new index for right_most_grid_cells
        if isempty(subgrid.grid)
            % No cells at this level.  If we are base, just use 1.
            % Otherwise use its current index.
            if isempty(beneath_cell)
                rmgi = 1;
            else
                rmgi = object.find_cell_in_list(object.right_most_grid_cells, beneath_cell);
            end
            
            %Ok, this is a replacement operation.
            object.right_most_grid_cells{ rmgi } = NewCell;
            if isempty(beneath_cell)
                %Only notify if a new cell was added.
                notify(object, 'AddedOuterCell', GridSingleCellEventDetails(rmgi))
            end
        else
            cell_in_rmg = subgrid.grid{ size(subgrid.grid, 2) };
            while size(cell_in_rmg.grid, 2) ~= 0
                cell_in_rmg = cell_in_rmg.grid{ size(cell_in_rmg.grid, 2) };
            end
            rmgi = object.find_cell_in_list(object.right_most_grid_cells, cell_in_rmg);
            
            %Since this is now an addition to the right most list, append.
            object.right_most_grid_cells = {object.right_most_grid_cells{1:rmgi} NewCell object.right_most_grid_cells{(rmgi+1):size(object.right_most_grid_cells, 2)}};
            rmgi = rmgi + 1;
    
            %This is always an addition.  So notify.
            notify(object, 'AddedOuterCell', GridSingleCellEventDetails(rmgi))
        end
        
        subgrid.grid{ size(subgrid.grid, 2)+1 } = NewCell;
    else
        assert(false, 'Add support for non-appending action');
    end

    notify(object, 'StructureChanged');

end

