function displayObject(obj)
%displayObject  Display content of a variable
%
%   Hidden method of dlarray.

%   Copyright 2019-2020 The MathWorks, Inc.

formatSpacing = get(0,'FormatSpacing');
if strcmp(formatSpacing,'compact')
    spacingline = '';
    looseSpace = 0;
else
    spacingline = '\n';
    looseSpace = 1;
end

sz = size(obj);

by = iGetDimensionJoinSymbol();
if hasFormat(obj)
    names = dims(obj);
    
    if numel(sz)<numel(names)
        % Pad with ones
        sz((end+1):numel(names)) = 1;
    end
    
    % Build combined size + dimension name string
    names = arrayfun(@string, names);
    joiner = " " + by + " ";
    description = join(sz + "(" + names + ")", joiner);
else
    % Build size string
    description = join(string(sz), by);
end

cls = matlab.mixin.CustomDisplay.getClassNameForHeader(obj);
objdata = extractdata(obj);
details = iGetDetails(objdata,cls);
header = sprintf('  %s%s%s\n', description, details, cls);
fprintf('%s',header);
fprintf(spacingline);

disp(objdata)

% Display header again if enough data was displayed
if iEstimateNumberOfLines(sz,looseSpace) > 50
    fprintf('%s',header);
    fprintf(spacingline);
end
end

function details = iGetDetails(data,template)
cls = underlyingType(data);
if isa(data,'gpuArray')
    device = replace(template,"dlarray","gpuArray");
else
    device = "";
end
details = " ";
if ~strcmp(cls,'double')
    formattedClass = replace(template,"dlarray",cls);
    details = details + formattedClass + " ";
end
if strlength(device) > 0
    details = details + device + " ";
end
end

function height = iEstimateNumberOfLines(objSize,looseSpace)
total = prod(objSize);
width = objSize(2);
height = total/width;

lineWrapWidth = 10; % a heuristic
if width > lineWrapWidth
    lineWrapHeaderSize = 1 + 2*looseSpace;
    height = (height+lineWrapHeaderSize)*ceil(width/lineWrapWidth);
end

if numel(objSize) > 2
    numSlices = prod(objSize(3:end));
    sliceHeaderSize = 1 + 2*looseSpace;
    height = height + sliceHeaderSize*numSlices;
end
end

function by = iGetDimensionJoinSymbol()
by = matlab.internal.display.getDimensionSpecifier;
end
