function varargout = dctProfTempDataManager(actionName, varargin)
; %#ok<NOSEM> %ok undocumented

% Generates director name unique to each instance of a client matlab and sets
% up the temporary file manager in the Profiler java singleton.
% Also sets up hidden(by default) figure for image generation.

% No filenames are generated by this manager as file names are specific to
% each type of figure being created and resides in the dctMpiProfHelpers
% file.
%   Copyright 2007-2012 The MathWorks, Inc.
%     

if nargout >= 1
    varargout = cell(max(nargout, 1), 1);
end

javaTempFileManager = com.mathworks.mde.profiler.Profiler.getTempFilesManager;
% Get the
profilerTempDir = char(javaTempFileManager.getTempLocation());
persistent sCurFig;
% this reference to figure is re initialized by finding the hidden figure
% if it already exists via nInitFindFigureHandle(). Initialization occurs
% only on actions related to figures.
%

switch(actionName)
    %
    case 'removeAllFiles'
        % undocumented api for removing temp files in matlab
        % Tests to see if java handles deletion of non existent temp file.
        iRemoveAllTempFiles(profilerTempDir, varargin{:});
        varargout{1} = '';

    case 'getTempDir'
        %  Returns a valid temp directory name unique to this matlab instance
        %  If directory has not been assigned new name is generated
        if isempty(profilerTempDir)
            profilerTempDir = nCreateNewTempDir();
        end
        varargout{1} = profilerTempDir;
        
    case 'newTempDir'
        % also creates a new empty figure ready for generating images
        varargout{1} = nCreateNewTempDir();
        nCreateNewFig();


        % *******************Figure management***************************
       
    case 'getEmptyFig'
        nInitFindFigHandle();
        varargout{1} = nGetEmptyFig();

    case 'closeFig'
        nInitFindFigHandle();
        
        if ~isempty(sCurFig)&&ishandle(sCurFig)
        iRunWithShowHiddenHandles(@close, {sCurFig});
        end

    case 'getCurrentFig'
        nInitFindFigHandle();
        [varargout{1}, curAxis]= nGetCurrentProfilerFigAndAxis();
        if nargout == 2
            varargout{2} = curAxis;
        end
    otherwise
        error(message('parallel:lang:mpi:ProfTempDataManager'));

 
end

% %%--------------------------------------------------------------
% insure we have a reference to the sCurFig if its made 
% %%--------------------------------------------------------------
    function nInitFindFigHandle()
    if isempty(sCurFig) || ~ishandle(sCurFig)
        sCurFig = iFindHiddenFig('mpiPlotFig');
        if numel(sCurFig) > 1
            sCurFig = sCurFig(1);
            xtraFig = sCurFig(2:end);
            delete(xtraFig);
        end
    end
    end

% %%--------------------------------------------------------------
% nCreateNewTempDir(profilerTempDir)
% %%--------------------------------------------------------------
    function profilerTempDir = nCreateNewTempDir()
    % the java side will remove all files in previous temp directory
    profilerTempDir = iGenerateUniqueTempDirectoryName();
    javaTempFileManager.setTempLocation(profilerTempDir);
    end

% %%--------------------------------------------------------------
% returns an empty figure. if not already created, a new figure window is
% created.
% %%--------------------------------------------------------------
    function emptyFig = nGetEmptyFig()
    if isempty(sCurFig) || ~ishandle(sCurFig)
        sCurFig = iCreateNewFig([]);
    end
    % reuse the current figure window
    % by removing all its children
    ch = get(sCurFig, 'Children');
    iRunWithShowHiddenHandles(@delete, {ch});
    
    emptyFig = sCurFig;

    end

% %%--------------------------------------------------------------
% creates a new figure. if not already created, a new figure window is
% created.
% %%--------------------------------------------------------------
    function nCreateNewFig(varargin)
    sCurFig = iCreateNewFig(sCurFig, varargin{:});
    end


%--------------------------------------------------------------------------
%--------------------------------------------------------------------------
    function [cFig, cAxis]= nGetCurrentProfilerFigAndAxis()
    if ~ishandle(sCurFig)
        nCreateNewFig();
    end

    cFig = sCurFig;
    % ensures figure has an axis
    cAxis = gca(cFig);
    % note gca always checks the current figure which will be
    % hidden from user.
    end

end


%--------------------------------------------------------------------------
%--------------------------------------------------------------------------
function iRemoveAllTempFiles(tempDirPath)
if ~isempty(tempDirPath)
    % delete everything in this temp directory
    delete([tempDirPath '*.*']);
    successrm = rmdir(tempDirPath);
    if ~successrm
        warning(message('parallel:lang:mpi:ProfTempFileManager', tempDirPath));
    end
end
end

%--------------------------------------------------------------------------
%--------------------------------------------------------------------------
function tmpname = iGenerateUniqueTempDirectoryName()
% parsing tempname to get a temp directory starting with MPIProfiler.
prevstate = warning('off', 'MATLAB:MKDIR:DirectoryExists');
% get the previous warning state
prevstate = prevstate.state;

initdir = [tempdir 'MPIProfiler'];

% Make sure we get a valid directory that is new
for i=1:100
    [~, thename] = fileparts(tempname);
    tmpname = [initdir, thename, filesep];

    if ~exist(tmpname, 'dir')
        mkdir(tmpname);
        % directory already exists?
        break;
    end
end

%restore the previous warning state
warning(prevstate, 'MATLAB:MKDIR:DirectoryExists');
end


%--------------------------------------------------------------------------
%--------------------------------------------------------------------------
function newFig = iCreateNewFig(curFig, figSize)

if nargin<2
    figSize = 0.3;
end
% ensure we create a new window even if window exists from before
if ~isempty(curFig) && ishandle(curFig)
    close(curFig);
end
newFig = figure('Units', 'normal','position', [0 0 figSize figSize],...
    'Visible', 'off',...
    'HandleVisibility', 'off',...
    'IntegerHandle', 'off',...
    'tag', 'mpiPlotFig');
end

%--------------------------------------------------------------------------
%--------------------------------------------------------------------------
function foundFig = iFindHiddenFig(figName)

foundFig = iRunWithShowHiddenHandles(@findobj, {'-depth', 1, 'tag', figName});
end


%--------------------------------------------------------------------------
%--------------------------------------------------------------------------
function varargout = iRunWithShowHiddenHandles(fcnHandle, cellArgs)
oldvalue = get(0, 'ShowHiddenHandles');
set(0, 'ShowHiddenHandles', 'on');
try
    if nargout > 0
        varargout{:} = fcnHandle(cellArgs{:});
    else
        fcnHandle(cellArgs{:})
    end
    err = [];
catch exception
    err = exception;
end
set(0, 'ShowHiddenHandles', oldvalue);
if ~isempty(err)
    rethrow(err);
end


end



