%

% Copyright 2017-2021 The MathWorks, Inc.
function signalData = castSignalData(this, signalData, signal, busStruct)
    import xls.internal.reader.*;
    import xls.internal.SignalClassifications;
    classification = signal.Classification;
    if signal.isExplicitBus
        signalData = castBusData(signalData, signal, busStruct);
    else
        type = signal.Type;
        if strlength(type) > 0
            if classification == SignalClassifications.Bus
                classification = signal.Subclass;
            end

            if classification == SignalClassifications.BuiltIn
                signalData = castBuiltInData(signalData, type);
            elseif classification == SignalClassifications.Enum
                signalData = enumReader(signalData, type);
            elseif classification == SignalClassifications.FixedPoint
                signalData = fixedPointReader(signalData, type, this.getContext(this.Model));
            elseif classification == SignalClassifications.Alias
                signalData = aliasReader(signalData, type, this.Model);
            end
        end
    end
end

function signalData = castBuiltInData(signalData, type)
    if isstring(signalData)
        signalData = fillmissing(signalData, 'constant', "");
        return; % data already correct type
    elseif strcmpi(type, 'string')
        signalData = string(signalData);
        return;
    end

    if strcmpi(type, xls.internal.ReadTable.Boolean) % Simulink naming convention
        type = 'logical';
    end
    signalData = cast(signalData, lower(type));
end

function signalData = castBusData(signalData, signal, busStruct)
    import xls.internal.Bus;
    import xls.internal.reader.*;
    busField = Bus.getField(busStruct, signal.PathName);
    signal.validateComplexity(busField);
    signal.validateDimensions(busField);

    if isenum(busField.Data)
        signalData = enumReader(signalData, class(busField.Data));
    elseif ~isstring(signalData)
        signalData = cast(signalData, 'like', busField.Data);
    end
end
