function outputTemplateFile = saveTemplate(obj, destinationTemplate)
%

%   Copyright 2019-2020 The MathWorks, Inc.

    modelName = get_param(obj, 'Name');
    metadata = get_param(obj, 'TemplateMetadata');

    thumbnailFile =  metadata.template.thumbnail;
    if strcmp(thumbnailFile, metadata.template.fullFilePath)
        unpackedLocation = tempname;
        mkdir(unpackedLocation);
        thumbnailFile = fullfile(unpackedLocation, 'thumbnail.png');
        originalTemplate = matlab.internal.project.packaging.PackageReader(get_param(obj, 'TemplateFilePath'));
        originalTemplate.extract('Thumbnail', thumbnailFile);
    end

    outputTemplateFile = sltemplate.internal.exportModelToTemplate( ...
        modelName, ...
        destinationTemplate, ...
        'Title', metadata.core.title, ...
        'Author', metadata.core.author, ...
        'Description', metadata.core.description, ...
        'Group', metadata.core.group, ...
        'ThumbnailFile', thumbnailFile, ...
        'WarningHandler', @warning);

    [mfModel, templateMetadata] = sltemplate.internal.extractTemplateMetadata(modelName);
    set_param(modelName, "TemplateModel", mfModel);
    set_param(modelName, "TemplateMetadata", templateMetadata);

    % Set the name of the model to be the same as the template
    [~, templateName, ~] = fileparts(outputTemplateFile);
    set_param(obj, 'Name', templateName);

    % Clear the dirty flag
    set_param(templateName, 'Dirty', 'off');
end
