function addBuildDependenciesToBuildInfo(buildInfo, buildDependencies, NameValueArgs)
%ADDBUILDDEPENDENCIESTOBUILDINFO adds the build information captured in the
%Target Framework target.BuildDependencies object to the specified
%RTW.BuildInfo object ready for build. Users can optionally resolve strings
%in the build dependencies using a provided VariableExpansion object, or if
%not provided, the default expansion.

%   Copyright 2020 The MathWorks, Inc.

    arguments        
        buildInfo (1,1) RTW.BuildInfo
        buildDependencies (1,1) target.BuildDependencies
        NameValueArgs.ExpandStrings (1,1) logical = true;
        NameValueArgs.VariableExpansion (1,1) targetframework.services.variableexpansion.VariableExpansion = targetframework.services.variableexpansion.createVariableExpansion();
    end
        
    if NameValueArgs.ExpandStrings
        expand = @(p) expandStringCellArray(p, NameValueArgs.VariableExpansion);
    else
        expand = @(p) p;
    end
    
    % Source files
    buildInfo.addSourceFiles(expand(buildDependencies.SourceFiles));
    
    % Include paths
    buildInfo.addIncludePaths(expand(buildDependencies.IncludePaths));
    
    % Include files
    buildInfo.addIncludeFiles(expand(buildDependencies.IncludeFiles));
    
    % Defines    
    buildInfo.addDefines(expand(buildDependencies.Defines));
    
    % Libraries
    linkObjects = createLinkObjectArguments(expand(buildDependencies.StaticLibraries));
    buildInfo.addLinkObjects(linkObjects{:});
    
    linkObjects = createLinkObjectArguments(expand(buildDependencies.SharedLibraries));
    buildInfo.addLinkObjects(linkObjects{:});
    
    linkObjects = createLinkObjectArguments(expand(buildDependencies.ObjectFiles));
    buildInfo.addLinkObjects(linkObjects{:});
    
    %This is undocumented and temporary as the compiler and linker flags
    %are specific to the toolchain compiler and linker. At some point these
    %could be auto-populated from the TF build tool representation or
    %associated with a build tool in the data model.
    buildInfo.addCompileFlags(expand(buildDependencies.CompilerFlags));
    buildInfo.addLinkFlags(expand(buildDependencies.LinkerFlags));
end

function arguments = createLinkObjectArguments(linkObjectStrings)

    [filenames, filepaths] = cellfun(@splitFilenameAndPath, linkObjectStrings, 'UniformOutput', false);
    arguments = {filenames, ...
                 filepaths, ...
                 repmat(RTW.BuildInfoLinkObj.DefaultLinkPriority, size(filenames)), ...
                 true(size(filenames)), ...
                 true(size(filenames))};
end

function [filename, filepath] = splitFilenameAndPath(linkObjectString)

    [filepath, name, ext] = fileparts(linkObjectString);    
    
    filename = [name ext];
    
end
        
function p = expandStringCellArray(p, variableExpansion)

    p = cellfun(@(f) variableExpansion.expand(f), p, 'UniformOutput', false);
end
