classdef ProfileReportTable < coder.profile.ProfileReportItem
    % PROFILEREPORTTABLE is an entry in the profiling report containing a table

    % Copyright 2021 The MathWorks, Inc.

    properties
        TableId;
        Headings;
        Rows;
        RowIndent;
        ColWidthsInPercent;
        ColAlignment;
        Offset;
        FootNotes;
        LinkStyles;
        ShrinkButton;
        SecNumber;
        WidthDec;
    end
    
    methods
        function obj = ProfileReportTable(name, tableInfo, footNotes, linksStyle, shrinkBtn, num, widthDec)
            obj = obj@coder.profile.ProfileReportItem(name);
            obj.ShrinkButton = shrinkBtn;
            obj.SecNumber = num;
            obj.WidthDec = widthDec;
            
            obj.TableId = tableInfo.tableId;
            obj.Headings = tableInfo.headings;
            obj.Rows = tableInfo.rows;
            obj.RowIndent = tableInfo.rowIndent;
            obj.ColWidthsInPercent = tableInfo.colWidthsInPercent;
            obj.ColAlignment = tableInfo.colAlignment;
            obj.Offset = tableInfo.Offset;
            
            obj.FootNotes = footNotes;
            obj.LinkStyles = linksStyle;
        end
        
        function build(this, report, ~)
            tableHtml = report.generateTableTree(this.Headings, this.Rows, ...
                this.RowIndent, this.ColWidthsInPercent, this.ColAlignment, ...
                                              this.TableId, this.Offset, 'results');
            
            notesHtml = '';
            if ~isempty(this.FootNotes) && this.FootNotes.length > 0
                notesHtml = '<br><p><b>Notes:</b></p>';
                values = this.FootNotes.values;
                numbers = zeros(size(values));
                for i=1:length(numbers)
                    numbers(i) = values{i}.Number;
                end
                [numbers, sortIdx] = sort(numbers);
                values =  values(sortIdx);
                for i=1:length(numbers)
                    notesHtml = sprintf('%s&#91;<a name = "%s">%d</a>&#93; %s<br>',...
                        notesHtml, ...
                        values{i}.Ref, values{i}.Number, ....
                        values{i}.Text);
                end
            end
            if ~isempty(notesHtml)
                tableHtml = sprintf('%s\n%s', tableHtml, notesHtml);
            end
            if ~isempty(this.LinkStyles)
                tableHtml = sprintf('%s%s', tableHtml, this.LinkStyles);
            end
            
            report.addCustomizedSection(this.SectionName, tableHtml, this.ShrinkButton, this.SecNumber, this.WidthDec);
        end
    end
    
end
