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);
description = deep.internal.dlarray.buildSizeString(obj);

cls = matlab.mixin.CustomDisplay.getClassNameForHeader(obj);

objdata = gatherData(obj.FormattedData);

isBlank = isa(objdata, 'deep.internal.blank');
if isBlank
    objdata = objdata.EmptyData;
elseif ~isempty(obj.ViewToDataMap)
    objdata = permute(objdata, obj.ViewToDataMap);
end

details = iGetDetails(objdata,cls,isBlank);
header = sprintf('  %s%s%s\n', description, details, cls);
fprintf('%s',header);
fprintf(spacingline);

if isBlank
    disp("(" + getString(message('deep:blank:NoValues')) + ")")
else
    disp(objdata)

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

function details = iGetDetails(data,template,isBlank)
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
if isBlank
    details = " blank" + details;
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
