package de.ugoe.cs.swe.exercises.lectureevent;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.Vector;
import org.eclipse.jface.dialogs.IMessageProvider;
import org.eclipse.jface.dialogs.TitleAreaDialog;
import org.eclipse.jface.resource.JFaceResources;
import org.eclipse.jface.viewers.StructuredSelection;
import org.eclipse.jface.viewers.TableViewer;
import org.eclipse.jface.viewers.TableViewerColumn;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.SelectionListener;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Combo;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.Text;

import de.ugoe.cs.swe.exercises.lecture.Lecture;
import de.ugoe.cs.swe.exercises.lecturer.Lecturer;
import de.ugoe.cs.swe.exercises.lecturer.LecturerContentProvider;
import de.ugoe.cs.swe.exercises.lecturer.LecturerLabelProvider;

public class LectureEventEditDialog extends TitleAreaDialog {

	private Text editYear;
	private int comboresultIsSummerSemester;
	private int comboresultLecture;
	private int[] lectureEvent = {-1, -1, -1};
	int[] lecturesListId;
	private Lecturer[] lecturerList;
	private TableViewer viewerLecturers;
	private ArrayList<Lecturer> selLecturers;
	
	private Shell shell;

	private Lecture lecture = new Lecture(null);
	private ArrayList<Lecture> lectures = new ArrayList<Lecture>();

	public LectureEventEditDialog(Shell parentShell, LectureEvent lectureEvent) {
		super(parentShell);
		super.setShellStyle(0);
		shell = parentShell;
		shell.setEnabled(false);
		int SSint;
		if(lectureEvent.getIsSummerSemester() == true)
			SSint = 0;
		else
			SSint = 1;
		this.lectureEvent = new int[] {lectureEvent.getSemester(), SSint, getLectureIndex(lectureEvent.getLecture().getId())};
		this.selLecturers = lectureEvent.getLecturers();
		this.comboresultIsSummerSemester = SSint;
		this.comboresultLecture = this.lectureEvent[2];
	}
	
	public Lecturer[] getLecturerList() {
		return lecturerList;
	}

	public int[] getLectureEvent() {
		return lectureEvent;
	}

	public LectureEventEditDialog(Shell parentShell) {
		super(parentShell);
	}

	@Override
	protected Control createContents(Composite parent) {
		parent.getShell().setSize(650, 500);
		int x = shell.getLocation().x + (shell.getSize().x - parent.getShell().getSize().x)/2;
		int y = shell.getLocation().y + (shell.getSize().y - parent.getShell().getSize().y)/2;
		parent.getShell().setLocation(x, y);
		
		Control contents = super.createContents(parent);
		setTitle("Add a new lecture event");
		setMessage("Please enter all the data for the new lecture Event",
				IMessageProvider.INFORMATION);
		return contents;
	}

	@SuppressWarnings("static-access")
	@Override
	protected Control createDialogArea(Composite parent) {
		GridLayout layout = new GridLayout();
		layout.numColumns = 2;
		parent.setLayout(layout);
		Label labelYear = new Label(parent, SWT.NONE);
		labelYear.setText("Year");
		Text textboxYear = new Text(parent, SWT.BORDER);
		textboxYear.setLayoutData(new GridData(GridData.GRAB_HORIZONTAL
				| GridData.HORIZONTAL_ALIGN_FILL));
		textboxYear.setText(String.valueOf(lectureEvent[0]));
		textboxYear.addListener(SWT.Verify, new Listener() {
		      public void handleEvent(Event e) {
		        String string = e.text;
		        char[] chars = new char[string.length()];
		        string.getChars(0, chars.length, chars, 0);
		        for (int i = 0; i < chars.length; i++) {
		          if (!('0' <= chars[i] && chars[i] <= '9')) {
		            e.doit = false;
		            return;
		          }
		        }
		      }
		    });
		editYear = textboxYear;

		Label labelIsSummerSemester = new Label(parent, SWT.NONE);
		labelIsSummerSemester.setText("SS/WS");

		final Combo comboIsSummerSemester = new Combo(parent, SWT.READ_ONLY);
		comboIsSummerSemester.setItems(new String[] { "Summer semester", "Winter semester" });
		comboIsSummerSemester.setSize(200, 200);
		comboIsSummerSemester.select(lectureEvent[1]);

		comboIsSummerSemester.addSelectionListener(new SelectionListener() {
			public void widgetSelected(SelectionEvent e) {
				comboresultIsSummerSemester = comboIsSummerSemester.getSelectionIndex();

			}

			public void widgetDefaultSelected(SelectionEvent e) {
				comboresultIsSummerSemester = -1;
			}
		});

		Label labelLecture = new Label(parent, SWT.NONE);
		labelLecture.setText("Lecture");
		lectures = lecture.all();
		String[] lecturesList = new String[lectures.toArray().length];
		lecturesListId = new int[lectures.toArray().length];

		for (int i = 0; i < lecturesList.length; i++) {
			lecturesList[i] = lectures.get(i).getName();
			lecturesListId[i] = lectures.get(i).getId();
		}

		final Combo comboLecture = new Combo(parent, SWT.READ_ONLY);
		comboLecture.setItems(lecturesList);
		comboLecture.setSize(200, 200);
		comboLecture.select(lectureEvent[2]);
		comboLecture.addSelectionListener(new SelectionListener() {
			public void widgetSelected(SelectionEvent e) {
				comboresultLecture = comboLecture.getSelectionIndex();
			}

			public void widgetDefaultSelected(SelectionEvent e) {
				comboresultLecture = -1;
			}
		});

		Label labelLecturerTable = new Label(parent, SWT.NONE);
		labelLecturerTable.setText("Lecturer:");
		
		 viewerLecturers = new TableViewer(parent, SWT.MULTI | SWT.H_SCROLL
				| SWT.V_SCROLL | SWT.BORDER);
		CreateLecturerColumns(viewerLecturers);
		viewerLecturers.setContentProvider(new LecturerContentProvider());
		viewerLecturers.setLabelProvider(new LecturerLabelProvider());
		viewerLecturers.setInput(getShell());
		
		viewerLecturers.getTable().select(getSelected());

		GridData gridData = new GridData();
		gridData.verticalAlignment = GridData.FILL;
		gridData.horizontalSpan = 2;
		gridData.grabExcessHorizontalSpace = true;
		gridData.grabExcessVerticalSpace = true;
		gridData.horizontalAlignment = GridData.FILL;
		viewerLecturers.getControl().setLayoutData(gridData);

		return parent;

	}

	@Override
	protected void createButtonsForButtonBar(Composite parent) {
		((GridLayout) parent.getLayout()).numColumns = 2;

		GridData buttonlayout = new GridData(SWT.LEFT, SWT.BEGINNING, false,
				false);
		buttonlayout.minimumWidth = 200;
		Button buttonOk = new Button(parent, SWT.PUSH);
		buttonOk.setText("OK");
		buttonOk.setFont(JFaceResources.getDialogFont());
		buttonOk.setLayoutData(buttonlayout);
		buttonOk.addSelectionListener(new SelectionAdapter() {
			@Override
			public void widgetSelected(SelectionEvent e) {

				if (editYear.getText().length() != 0 && comboresultIsSummerSemester >= 0 && comboresultLecture >= 0) {
					lectureEvent[0] = Integer.parseInt(editYear.getText());
					lectureEvent[1] = comboresultIsSummerSemester;
					lectureEvent[2] = lecturesListId[comboresultLecture];

					StructuredSelection sel = ((StructuredSelection) viewerLecturers
							.getSelection());
					
					lecturerList = new Lecturer[sel.size()];
					Object[] fuckdisshit = sel.toArray();
					for ( int i=0 ; i<fuckdisshit.length ; i++) {
					lecturerList[i] = (Lecturer) fuckdisshit[i];
					}
					shell.setEnabled(true);
					close();

				} else {
					setErrorMessage("Please fill out all the data");
				}
			}
		});
		Button buttonCancel = new Button(parent, SWT.PUSH);
		buttonCancel.setText("Cancel");
		buttonCancel.setFont(JFaceResources.getDialogFont());
		buttonCancel.setLayoutData(buttonlayout);
		buttonCancel.addSelectionListener(new SelectionAdapter() {
			@Override
			public void widgetSelected(SelectionEvent e) {
				lectureEvent = new int[] {-1,-1,-1};
				shell.setEnabled(true);
				close();
			}
		});
	}

	private void CreateLecturerColumns(TableViewer viewer) {
		String[] titles = { "Title", "First Name", "Last Name" };
		int[] bounds = {200, 200, 200 };

		for (int i = 0; i < titles.length; i++) {
			TableViewerColumn column = new TableViewerColumn(viewer, SWT.NONE);
			column.getColumn().setText(titles[i]);
			column.getColumn().setWidth(bounds[i]);
			Table table = viewer.getTable();
			table.setHeaderVisible(true);
			table.setLinesVisible(true);
		}
	}
	
	private int getLectureIndex(int lectureId) {
		ArrayList<Lecture> allLectures = Lecture.all();
		for(int i=0; i<allLectures.size();i++){
			if(lectureId == allLectures.get(i).getId()) {
				return i;
			}
		}
		return 0;
	}
	
	private int[] getSelected() {
		Vector<Integer> selection = new Vector<Integer>();
		Iterator<Lecturer> selIterator = selLecturers.iterator();
		ArrayList<Lecturer> allLecturers = Lecturer.all();
		while(selIterator.hasNext()) {
			Lecturer lecturer = selIterator.next();
			for(int i=0; i<allLecturers.size();i++){
				if(lecturer.getId() == allLecturers.get(i).getId()) {
					selection.add(i);
					break;
				}
			}
		}
		int[] list = new int[selection.size()];
		Object[] obj = selection.toArray();
		for(int i=0; i<list.length; i++) {
			list[i] = ((Integer)obj[i]).intValue();
		}
		return list;
	}
}