%

% Copyright 2017-2018 The MathWorks, Inc.
function addTimeSeries(this, vValues, signalNames, elementName, parsedElem, isBus)
    import xls.internal.WriteTable;
    shouldEscape = WriteTable.nameNeedsEscaping(elementName);

    for x = 1:size(vValues, 2)
    	values = vValues(:, x);
        parsedVar = WriteTable.getParsedVar(values, signalNames(x));
        dataValues = WriteTable.getParsedVarData(parsedVar, @(var) var.getDataValues);
        if isempty(dataValues)
            return; % no data to write
        end

        headers = this.createColumnHeaders(parsedVar, dataValues, parsedElem);
        this.M{:, end+1 : end+numel(headers)} = ""; % preallocate table
        % only first header needs extra metadata
        column = locCreateColumn(this, parsedElem, parsedVar, headers(1), ...
            elementName, shouldEscape, isBus);
        this.addColumnToTable(column);

        % add remaining columns for dimensions and complexity
        this.addExtraHeaders(headers);
        if isa(parsedVar, 'xls.internal.import.FcnCallInputParser')
            partitionFcnCall(this);
        end
    end
end

function partitionFcnCall(this)
    this.stablePartition(this.FcnCallCol, size(this.M, 2));
    this.FcnCallCol = this.FcnCallCol + 1;
end

function column = locCreateColumn(this, parsedElem, parsedVar, header, ...
        elementName, shouldEscape, isBus)
    column = xls.internal.Column(header);

    if this.PreserveTolerance
        sigName = header;
        rdr = xls.internal.reader.getReader(parsedVar.getDataValues);
        % use element name for multi-dimensional and complex signals
        if length(parsedVar.getSampleDims) > 1 || rdr.isComplex
            sigName = elementName;
        end
        column.Tolerance = this.getToleranceFromCache(sigName, parsedElem, isBus);
    else
        column.Tolerance = this.getGlobalTolerance();
    end
    
    column.setBlockPathAndPortIndex(parsedElem);

    if shouldEscape
        column.ExplicitName = elementName;
    end
    column.setType(parsedVar);
    column.setInterp(parsedVar);
    column.setUnit(parsedVar);
    if this.SourceWriter.needsToWrite(parsedVar)
        this.SourceWriter.write(column, parsedVar);
    end

    if this.SimulationWriter.needsToWrite(parsedVar)
        this.SimulationWriter.write(column, parsedVar);
    end
end


