package ru.rsdn.patterns.mvc.samples;

import java.util.Collection;

import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.ListViewer;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.List;

import ru.rsdn.patterns.mvc.model.ListModel;
import ru.rsdn.patterns.mvc.model.Model;
import ru.rsdn.patterns.mvc.view.ListView;

/**
 * Представление списка переключателей
 */
public class ListSwitchView extends ListView<Switch> {
	private final ListViewer viewer;

	/**
	 * Конструктор
	 * @param parent композит
	 */
	public ListSwitchView(Composite parent) {
		final Composite composite = new Composite(parent, SWT.NONE);
		composite.setLayout(new GridLayout());
		final List list = new List(composite, SWT.BORDER | SWT.H_SCROLL |
				SWT.V_SCROLL | SWT.MULTI);
		list.setLayoutData(new GridData(GridData.FILL_BOTH));
		viewer = new ListViewer(list);
		viewer.setContentProvider(new ListContentProvider<Switch>());
		final Button addButton = new Button(composite, SWT.PUSH);
		addButton.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
		addButton.setText("Добавить");
		addButton.addSelectionListener(new SelectionAdapter() {
			@Override
			public void widgetSelected(SelectionEvent e) {
				add(new Model<Switch>(new Switch()));
			}
		});
		final Button deleteButton = new Button(composite, SWT.PUSH);
		deleteButton.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
		deleteButton.setText("Удалить");
		deleteButton.addSelectionListener(new SelectionAdapter() {
			@SuppressWarnings("unchecked")
			@Override
			public void widgetSelected(SelectionEvent e) {
				final IStructuredSelection selection = (IStructuredSelection) viewer
						.getSelection();
				if (!selection.isEmpty())
					delete(selection.toList());
			}
		});
		final Button undoButton = new Button(composite, SWT.PUSH);
		undoButton.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
		undoButton.setText("Отмена");
		undoButton.addSelectionListener(new SelectionAdapter() {
			@Override
			public void widgetSelected(SelectionEvent e) {
				undo();
			}
		});
		final Button redoButton = new Button(composite, SWT.PUSH);
		redoButton.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
		redoButton.setText("Повтор");
		redoButton.addSelectionListener(new SelectionAdapter() {
			@Override
			public void widgetSelected(SelectionEvent e) {
				redo();
			}
		});
	}

	@Override
	public void setModel(ListModel<Switch> model) {
		super.setModel(model);
		viewer.setInput(model);
	}

	public void modelChanged(Model<Collection<Model<Switch>>> model) {
		viewer.setInput(model);
	}
}
