package com.pmease.quickbuild.plugin.artifact;

import java.io.File;

import org.apache.wicket.markup.html.panel.Panel;
import org.apache.wicket.model.Model;

import com.pmease.quickbuild.AccessDeniedException;
import com.pmease.quickbuild.Context;
import com.pmease.quickbuild.QuickbuildException;
import com.pmease.quickbuild.annotation.Editable;
import com.pmease.quickbuild.extensionpoint.support.BuildBasedGadget;
import com.pmease.quickbuild.extensionpoint.support.GadgetCategory;
import com.pmease.quickbuild.pluginsupport.PluginSettingHelper;
import com.pmease.quickbuild.security.ConfigurationPermission;
import com.pmease.quickbuild.security.SecurityHelper;
import com.pmease.quickbuild.web.component.DirectoryView;

@Editable(name="External Artifacts", category=GadgetCategory.ARTIFACTS_AND_HTML_REPORTS)
public class ExternalArtifactGadget extends BuildBasedGadget {

	private static final long serialVersionUID = 1L;

	@Override
	protected Panel renderBodyForBuild(String panelId) {
		if (SecurityHelper.hasPermission(ConfigurationPermission.ACCESS_ARTIFACTS.name())
				|| Context.getBuild().isRecommended() && SecurityHelper.hasPermission(ConfigurationPermission.ACCESS_RECOMMENDED_ARTIFACTS.name())) {
			ExternalArtifactSetting artifactSetting = (ExternalArtifactSetting) PluginSettingHelper.findConfigurationSetting(ArtifactPlugin.class, Context.getConfiguration(), true);
			if (artifactSetting != null) {
				final File externalArtifactsDir = new File(artifactSetting.getExternalDirectory());
				if (externalArtifactsDir.exists()) 
					return new DirectoryView(panelId, Model.of(externalArtifactsDir), SecurityHelper.hasPermission(ConfigurationPermission.BATCH_DOWNLOAD_ARTIFACTS.name()));
				else 
					throw new QuickbuildException("Can not find external artifacts directory: " + externalArtifactsDir.getAbsolutePath());
			} else {
				throw new QuickbuildException("External artifacts setting is not defined for configuration: " + Context.getConfiguration());				
			}
		} else {
			throw new AccessDeniedException("You do not have permission to " +
					"access configuration '" + Context.getConfiguration() + "'.");
		}
	}

}
