%

% Copyright 2018 The MathWorks, Inc.
function addParametersToTable(this, T)
    column = createColumn(this);
    paramCol = getParamCol(column, this);
    valueCol = getValueCol(paramCol);
    maskCol = getMaskCol(T, paramCol);
    this.M = getM(this.M, paramCol, valueCol, maskCol);
    this.D = getD(this, T);
    this.CurrentCol = this.CurrentCol + size(T, 2);
end

function column = createColumn(this)
    paramString = string(getString(message('sl_xls:Parameter:Parameters')));
    column = xls.internal.Column(paramString);
    if this.SimulationWriter.needsToWrite(paramString)
        this.SimulationWriter.write(column, paramString);
    end
end

function paramCol = getParamCol(column, this)
    [paramCol, this.TypesCol] = column.toStringArray(this.TypesCol);
    paramCol = this.enforceRectangularData('M', paramCol, "");
end

function valueCol = getValueCol(paramCol)
    valueCol = string(getString(message('sl_xls:Parameter:Value')));
    valueCol = makeRectangular(valueCol, numel(paramCol));
end

function maskCol = getMaskCol(T, paramCol)
    if size(T, 2) <= 2
        maskCol = string.empty;
    else
        maskCol = string(getString(message('sl_xls:Parameter:BlockPath')));
        maskCol = makeRectangular(maskCol, numel(paramCol));
    end
end

function col = makeRectangular(col, num)
    if num > 1
        col(num, 1) = "";
    end
end

function M = getM(M, paramCol, valueCol, maskCol)
    M = addvars(M, paramCol);
    M = addvars(M, valueCol);
    if ~isempty(maskCol)
        M = addvars(M, maskCol);
    end
end

function D = getD(this, T)
    valCol = xls.internal.ParametersRange.ValueCol;
    reader = xls.internal.reader.getReader(T{1,valCol});
    data = this.enforceRectangularData('D', T{:,valCol}, reader.getMissing);
    T = padWithMissing(T, data);
    this.D = xls.internal.UpdateExistingTables.concatTwoTables(this.D, T);
    D = this.D;
end

function T = padWithMissing(T, data)
    newRowsAdded = size(data, 1) - size(T, 1);
    if newRowsAdded >= 1
        miss = repmat({missing}, 1, size(T, 2));
        T(end+newRowsAdded, :) = table(miss{:});
        valCol = xls.internal.ParametersRange.ValueCol;
        T(:,valCol) = table(data);
    end
end
