/*
 *  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.controls;

import java.io.File;
import org.dbgl.exception.InvalidMountstringException;
import org.dbgl.gui.abstractdialog.BaseDialog;
import org.dbgl.model.conf.mount.DirMount;
import org.dbgl.model.conf.mount.ImageMount;
import org.dbgl.model.conf.mount.Mount;
import org.dbgl.model.conf.mount.PhysFsMount;
import org.dbgl.model.factory.MountFactory;
import org.dbgl.service.ImageService;
import org.dbgl.service.TextService;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.List;
import org.eclipse.swt.widgets.Text;


public class GrabButton {

	private final Button button;

	public GrabButton(Composite composite, Text text, List source, boolean isBooter) {
		button = BaseDialog.createImageButton(composite, TextService.getInstance().get("button.grab"), ImageService.IMG_GRAB);

		button.addSelectionListener(new SelectionAdapter() {
			public void widgetSelected(SelectionEvent event) {
				int index = source.getSelectionIndex();
				if (index == -1 && source.getItemCount() == 1) {
					source.select(0);
					index = 0;
				}
				if (index != -1) {
					try {
						Mount mnt = MountFactory.create(source.getItem(index));
						if (isBooter && mnt instanceof ImageMount) {
							text.setText(((ImageMount)mnt).getImgPaths()[0].getPath());
						} else {
							if (mnt instanceof DirMount)
								text.setText(((DirMount)mnt).getPath().getPath() + File.separatorChar);
							else if (mnt instanceof ImageMount)
								text.setText(((ImageMount)mnt).getImgPaths()[0].getPath() + File.separatorChar);
							else if (mnt instanceof PhysFsMount)
								text.setText(((PhysFsMount)mnt).getPath().getPath() + File.separatorChar);
						}
						text.selectAll();
						text.setFocus();
					} catch (InvalidMountstringException e1) {
						// nothing we can do
					}
				}
			}
		});
	}
}
