classdef RTEMainUtils < handle
%RTEMainUtils This class provides code writing for the RTE main generation 
%
%   This is an undocumented class. Its methods and properties are likely to
%   change without warning from one release to the next.

%   Copyright 2020 The MathWorks, Inc.

    properties
        cw
    end
    
    properties (Constant)
        DelimiterSet = {'""','<>'}
        CharsPerLine = 68
    end


    methods

        function this = RTEMainUtils(writer)
            this.cw = writer;
        end

    end

    methods

        function wHeaders(this, headers, delimiter)
            if ~any(strcmp(delimiter, this.DelimiterSet))
                warning(['Invalid delimiter ', delimiter, ...
                        ' for #include preprocessing directive.']);
            end

            headers = unique(headers);

            for header = headers
                this.cw.wLine('#include %s%s%s', delimiter(1), header, delimiter(2));
            end

        end


        function wMultiLineComment(this, comment)

            len = length(comment);
            if (len <= this.CharsPerLine)
                this.cw.wComment(comment);
            	return
            end
            
            endIdx = 0;
            while endIdx < len
                beginIdx = endIdx + 1;
                endIdx = min(beginIdx + this.CharsPerLine, len);
                while (~isspace(comment(endIdx)) && endIdx < len)
                    endIdx = endIdx + 1;
                end
                
                if beginIdx == 1
                    this.cw.wMultilineCommentStart(comment(beginIdx : endIdx));
                elseif endIdx >= len
                    this.cw.wMultilineCommentEnd(comment(beginIdx : endIdx));
                else
                    this.cw.wMultilineCommentMiddle(comment(beginIdx : endIdx));
                end
            end
            
        end

        function wFunctionDecl(this, returnType, fcnName, params)
            this.cw.wLine('%s;', getFcnPrototype(returnType, fcnName, params));
        end

    end

    methods(Static)
        function fcnPro = getFcnPrototype(returnType, fcnName, params)
            fcnPro = sprintf('%s %s(%s)', returnType, fcnName, strjoin(params, ', '));
        end
    end
end
