/*
 *  Copyright (C) 2006-2019  Ronald Blankendaal
 *
 *  This program is free software; you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation; either version 2 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
 */
package org.dbgl.gui.dialog;

import java.io.IOException;
import org.dbgl.gui.GeneralPurposeDialogs;
import org.dbgl.gui.abstractdialog.SizeControlledButtonDialog;
import org.dbgl.util.FilesUtils;
import org.dbgl.util.StringRelatedUtils;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.MouseAdapter;
import org.eclipse.swt.events.MouseEvent;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.widgets.List;
import org.eclipse.swt.widgets.Shell;


public class BrowseArchiveDialog extends SizeControlledButtonDialog<String> {

	private final String fileToBrowse_;
	private String[] executablesInArchive_;

	public BrowseArchiveDialog(Shell parent, String fileToBrowse) {
		super(parent, "archivebrowser");
		fileToBrowse_ = fileToBrowse;
	}

	@Override
	protected String getDialogTitle() {
		return text_.get("dialog.archivebrowser.title");
	}

	@Override
	protected boolean prepare() {
		try {
			executablesInArchive_ = FilesUtils.listExecutablesInZipOrIsoOrFat(fileToBrowse_);
			if (executablesInArchive_.length <= 0) {
				GeneralPurposeDialogs.warningMessage(getParent(), text_.get("dialog.archivebrowser.notice.noexe"));
				return false;
			}
		} catch (IOException e) {
			GeneralPurposeDialogs.warningMessage(getParent(), text_.get("dialog.archivebrowser.error.readarchive", new Object[] {fileToBrowse_, StringRelatedUtils.toString(e)}), e);
			return false;
		}
		return true;
	}

	@Override
	protected void onShellCreated() {
		contents_.setLayout(new FillLayout());

		List files = createList(contents_, SWT.V_SCROLL | SWT.BORDER, executablesInArchive_, 0);
		files.addMouseListener(new MouseAdapter() {
			public void mouseDoubleClick(MouseEvent event) {
				doChooseFile(files);
			}
		});

		createOkCancelButtons(new SelectionAdapter() {
			public void widgetSelected(SelectionEvent event) {
				doChooseFile(files);
			}
		});
	}

	private void doChooseFile(List files) {
		result_ = FilesUtils.determineFullArchiveName(fileToBrowse_, files.getItem(files.getSelectionIndex()));
		shell_.close();
	}
}
