%TempLocalFolder
% A helper class that maintains a local temporary folder. If this object is
% sent to a worker, the worker will not hold lifetime ownership over the
% temporary folder.

%   Copyright 2014-2016 The MathWorks, Inc.

classdef (Sealed, Hidden) TempLocalFolder < handle
    properties (SetAccess = immutable)
        Path; % The path to the temporary local folder.
    end
    
    properties (GetAccess = private, SetAccess = immutable, Transient)
        ShouldCleanup = false; % A flag that indicates if this instance is responsible for cleanup of the folder.
    end
    
    methods
        % Create a temporary local folder.
        function obj = TempLocalFolder
            obj.Path = matlab.mapreduce.internal.createTempLocalFolder();
            obj.ShouldCleanup = true;
        end
        
        function delete(obj)
            if obj.ShouldCleanup && exist(obj.Path, 'dir')
                [success, message, identifer] = rmdir(obj.Path, 's');
                if ~success
                    err = MException(identifer, '%s', message);
                    dctSchedulerMessage( 1, ...
                        'Failed to delete temporary folder ''%s'', original error: %s', obj.Path, err.getReport());
                end
            end
        end
    end
end
