classdef (Hidden = true) Checksum < handle 
    %CHECKSUM provides shared infrastructure for calculating, comparing and
    %   storing checksums.
    %
    %   This is an undocumented class. Its methods and properties are likely to
    %   change without warning from one release to the next.
    
    %   Copyright 2020-2021 The MathWorks, Inc.
        

    methods(Static, Access = 'public')
        
        function checksums = calculate(filepaths)
            
            checksums = cell(1,length(filepaths));
            for idx=1:length(filepaths)
                % ensure the file exists
                assert(isfile(filepaths{idx}), 'File not found. Cannot calculate checksum.');
                % calculate checksum, can currently only take a single file path
                checksums{idx} = builtin('_coder_compile_getMd5', filepaths{idx});
            end
            
        end
        
        function areEqual = equal(filepaths, targetChecksums)
            % calculate checksum(s)
            fileChecksums = coder.internal.utils.Checksum.calculate(filepaths);
            % compare values of calculated and target checksum(s)
            areEqual = all(isequal(fileChecksums, targetChecksums));
        end
        
        
        function infoStruct = dependencyChecksumsStruct(dependencies, codeDescriptorPath, startDir)
            
            % record the checksums for the dependencies
            [dependencyFolder, dependencyName, dependencyExtension] = fileparts(dependencies);
            
            % Remove the start of the path from the folder for each dependency
            % to get the relative path (and remove the trailing file
            % separator - this must be done separately in case there is an
            % an exact match between start of the path and the folder).
            dependencyFolder = extractAfter(dependencyFolder, startDir);
            dependencyFolder = extractAfter(dependencyFolder, filesep);
            
            dependencyInfo.Dependencies.Files = strcat(dependencyName, dependencyExtension);
            dependencyInfo.Dependencies.Dirs = dependencyFolder;
            dependencyInfo.Dependencies.Checksums = coder.internal.utils.Checksum.calculate(dependencies);
            
            %Add code descriptor checksum
            dependencyInfo.CodeDescriptorChecksum = coder.internal.utils.Checksum.calculate( {codeDescriptorPath} );
            
            infoStruct = dependencyInfo;

        end
        
        
    end
    
end
