function launchui(appname,varargin)
%

% Copyright 2016-2023 The MathWorks, Inc.

narginchk(1,3);

import matlab.internal.capability.Capability;

% Check inputs, convert from string to char if needed
N = numel(varargin);
for n = 1:N
validateattributes(varargin{n},{'char','string'},{'scalartext'}, ...
appname,'',n)
varargin{n} = char(varargin{n});
end

% Open new project in UI
if N==0
% Opening UI to new project, for now this requires Java...
Capability.require([Capability.Swing, Capability.ComplexSwing]);
if usejava('swing')
com.mathworks.project.impl.plugin.PluginManager.allowMatlabThreadUse;
fcn = noinputfcn(appname);
fcn();
else
error(message('Compiler:deploytool:OpenProjectRequiresDesktop'));
end
elseif N==1
% Help text
if (strcmp(varargin{1},'-?') || strcmp(varargin{1},'/?'))
help(appname)
return
end

% Must be a project reopen. Make sure this is a valid file and
% open up the UI
if isValidProject(varargin{1})
if usejava('swing')
open(varargin{1});
else
error(message('Compiler:deploytool:OpenProjectRequiresDesktop'));
end
else
error(message('Compiler:deploytool:invalidFirstInputOneInput', varargin{1}, appname));
end

else % N==2
% This must conform to either build or package syntax
if (strcmp('-build',varargin{1}) || strcmp('/build',varargin{1}))
if ~strcmp('hadoopCompiler', appname)
warning(message('Compiler:deploytool:DeploytoolFunctionalityToBeRemoved', appname));
end
compiler.internal.build.legacyProject(varargin{2});
elseif (strcmp('-package',varargin{1}) || strcmp('/package',varargin{1}))
if ~strcmp('hadoopCompiler', appname)
warning(message('Compiler:deploytool:DeploytoolFunctionalityToBeRemoved', appname));
end
compiler.internal.package.legacyProject(varargin{2});
else
% Two arguments and the first is non-conforming. Tell the user as such
error(message('Compiler:deploytool:invalidFirstInputTwoInputs', varargin{1}, appname));
end
end

function fcn = noinputfcn(appname)

switch appname
case 'deploytool'
fcn = @com.mathworks.toolbox.compiler.desktop.DeploytoolLaunchPad.launch;
case 'applicationCompiler'
fcn = @com.mathworks.toolbox.compiler.desktop.DeploytoolLaunchPad.startStandaloneTool;
case 'libraryCompiler'
fcn = @com.mathworks.toolbox.compiler.desktop.DeploytoolLaunchPad.startLibraryTool;
case 'hadoopCompiler'
fcn = @com.mathworks.toolbox.compiler.desktop.DeploytoolLaunchPad.startMapReduceTool;
case 'productionServerCompiler'
fcn = @com.mathworks.toolbox.compiler.desktop.DeploytoolLaunchPad.startArchiveTool;
case 'webAppCompiler'
fcn = @com.mathworks.toolbox.compiler.desktop.DeploytoolLaunchPad.startWebAppsTool;
otherwise
error(message('MATLAB:class:UndefinedFunctionOrVariable',appname))
end
end

function isValid = isValidProject(f)
isValid = exist(f,'file');
try
compiler.internal.readPRJStruct(f);
% If the PRJ could be loaded, this is valid
isValid = true;
catch
isValid = false;
end

end

end