package com.pmease.quickbuild.plugin.artifact;

import java.io.File;

import org.apache.wicket.Component;
import org.apache.wicket.markup.html.link.Link;
import org.apache.wicket.markup.html.panel.Fragment;
import org.apache.wicket.markup.html.panel.Panel;
import org.apache.wicket.model.Model;
import org.apache.wicket.request.IRequestCycle;
import org.apache.wicket.request.handler.resource.ResourceStreamRequestHandler;
import org.apache.wicket.util.resource.FileResourceStream;
import org.apache.wicket.util.resource.IResourceStream;

import com.pmease.quickbuild.security.ConfigurationPermission;
import com.pmease.quickbuild.security.SecurityHelper;
import com.pmease.quickbuild.util.FileUtils;
import com.pmease.quickbuild.web.component.DirectoryView;

@SuppressWarnings("serial")
public class ExternalArtifactSummaryPanel extends Panel {

	public ExternalArtifactSummaryPanel(String panelId, final File artifactsDir) {
		super(panelId);
		
		add(new DirectoryView("content", Model.of(artifactsDir), SecurityHelper.hasPermission(ConfigurationPermission.BATCH_DOWNLOAD_ARTIFACTS.name())) {

			@Override
			protected Component newTreeHeader(String id) {
				Fragment fragment = new Fragment(id, "headerFrag", ExternalArtifactSummaryPanel.this);
				
				fragment.add(new Link<Void>("download") {

					@Override
					protected void onConfigure() {
						super.onConfigure();
						setVisible(SecurityHelper.hasPermission(ConfigurationPermission.BATCH_DOWNLOAD_ARTIFACTS.name()));
					}

					@Override
					public void onClick() {
						final File tempFile = FileUtils.createTempFile("dirdownload");
						try {
							FileUtils.zip(artifactsDir, tempFile);

							IResourceStream resourceStream = new FileResourceStream(
									new org.apache.wicket.util.file.File(tempFile));

							getRequestCycle().scheduleRequestHandlerAfterCurrent(
									new ResourceStreamRequestHandler(resourceStream, "artifacts.zip") {
										
								@Override
								public void respond(IRequestCycle requestCycle) {
									try {
										super.respond(requestCycle);
									} finally {
										FileUtils.deleteFile(tempFile);
									}
								}

							});	
						} catch(Exception e) {
							FileUtils.deleteFile(tempFile);
						}
					}
					
				});
				
				return fragment;
			}
			
		});

	}

}
