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

import java.awt.Desktop;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.FileDialog;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.TableItem;
import org.eclipse.swt.widgets.Text;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.Label;
import de.ugoe.cs.swe.exercises.exercise.Exercise;
import de.ugoe.cs.swe.exercises.exercise.ExerciseSVN;
import de.ugoe.cs.swe.exercises.lecture.GUITreeView;
import de.ugoe.cs.swe.exercises.misc.CKeyword;
import de.ugoe.cs.swe.exercises.misc.KeywordsCompositeExtender;

import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.TableColumn;
import org.eclipse.swt.dnd.DND;
import org.eclipse.swt.dnd.DragSource;
import org.eclipse.swt.dnd.DragSourceEvent;
import org.eclipse.swt.dnd.DragSourceListener;
import org.eclipse.swt.dnd.DropTarget;
import org.eclipse.swt.dnd.DropTargetAdapter;
import org.eclipse.swt.dnd.DropTargetEvent;
import org.eclipse.swt.dnd.TextTransfer;
import org.eclipse.swt.dnd.Transfer;
import org.eclipse.swt.events.ModifyListener;
import org.eclipse.swt.events.ModifyEvent;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.widgets.Group;
import org.eclipse.swt.custom.SashForm;

public class ExerciseSheetComposite extends Composite {

	private ExerciseSheet selected = null;
	private KeywordsCompositeExtender keywordsExtender;
	private Text sheetNumberText;
	private Text complexityText;
	private Table currentExercisesTable;
	private Table possibleExercisesTable;
	private Label lectureEventLabel;
	private Button examinationCheck;
	private TableColumn currentTitle;
	private TableColumn currentComplexity;
	private TableColumn possibleTitle;
	private TableColumn possibleComplexity;
	private Group group;
	private SashForm sashForm;
	private Button generateButton;
	private Button pdfButton;
	private Label lblOfExercises;
	private Text numOfExercisesText;
	private Button delPDF;
	private SashForm sashForm_1;
	private Button previewButton;
	private Button solutionButton;

	class ExerciseDragger implements DragSourceListener {
		Table viewer;
		ExerciseSheetComposite composite;
		String data;
		boolean remove;

		public ExerciseDragger(ExerciseSheetComposite composite, Table viewer,
				boolean remove) {
			this.viewer = viewer;
			this.composite = composite;
			this.remove = remove;
		}

		public void dragStart(DragSourceEvent event) {
			event.doit = (selected != null);
		}

		public void dragSetData(DragSourceEvent event) {
			data = "";
			TableItem[] sel = viewer.getSelection();

			for (int i = 0; i < sel.length; i++) {
				Exercise exercise = (Exercise) sel[i].getData();
				data += String.valueOf(exercise.getId()) + ",";
			}

			event.data = data;
		}

		public void dragFinished(DragSourceEvent event) {
			if (event.detail == DND.DROP_MOVE && remove) {
				String[] exerciseList = data.split(",");
				Exercise itemToDelete;
				for (int i = 0; i < exerciseList.length; i++) {
					itemToDelete = Exercise.getItem(Integer
							.parseInt(exerciseList[i]));
					selected.removeExercise(itemToDelete);
				}
				composite.refreshData();
			}
		}
	}

	class ExerciseDropper extends DropTargetAdapter {
		ExerciseSheetComposite composite;
		boolean add;

		public ExerciseDropper(ExerciseSheetComposite composite, boolean add) {
			this.composite = composite;
			this.add = add;
		}

		public void dragOver(DropTargetEvent event) {
			event.feedback = DND.FEEDBACK_SCROLL | DND.FEEDBACK_SELECT;
		}

		public void drop(DropTargetEvent event) {
			if (event.data == null) {
				event.detail = DND.DROP_NONE;
				return;
			}
			if (!add)
				return;
			String[] exerciseList = ((String) event.data).split(",");
			Exercise itemToAdd;
			for (int i = 0; i < exerciseList.length; i++) {
				itemToAdd = Exercise.getItem(Integer.parseInt(exerciseList[i]));
				selected.addExercise(itemToAdd);
			}
			composite.refreshData();
		}
	}

	/**
	 * Create the composite.
	 * 
	 * @param this
	 * @param style
	 */
	public ExerciseSheetComposite(Composite parent, int style) {
		super(parent, SWT.NONE);
		setLayout(new GridLayout(4, true));

		group = new Group(this, SWT.NONE);
		group.setLayout(new GridLayout(2, false));
		group.setLayoutData(new GridData(SWT.CENTER, SWT.CENTER, false, false,
				2, 6));

		Label sheetLabel = new Label(group, SWT.NONE);
		sheetLabel.setLayoutData(new GridData(SWT.LEFT, SWT.BOTTOM, false,
				true, 1, 1));
		sheetLabel.setText("Sheet #");

		sheetNumberText = new Text(group, SWT.BORDER);
		sheetNumberText.setLayoutData(new GridData(SWT.LEFT, SWT.BOTTOM, false,
				false, 1, 1));

		lectureEventLabel = new Label(group, SWT.NONE);
		lectureEventLabel.setLayoutData(new GridData(SWT.FILL, SWT.CENTER,
				false, false, 2, 1));
		lectureEventLabel.setText("Lecture Event");

		Label complexityLabel = new Label(group, SWT.NONE);
		complexityLabel.setText("maximal complexity:");

		complexityText = new Text(group, SWT.BORDER);

		lblOfExercises = new Label(group, SWT.NONE);
		lblOfExercises.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false,
				false, 1, 1));
		lblOfExercises.setText("# of exercises");

		numOfExercisesText = new Text(group, SWT.BORDER);
		numOfExercisesText.setLayoutData(new GridData(SWT.LEFT, SWT.CENTER,
				true, false, 1, 1));

		examinationCheck = new Button(group, SWT.CHECK);
		examinationCheck.addSelectionListener(new SelectionAdapter() {
			@Override
			public void widgetSelected(SelectionEvent e) {
				selected.setExamination(examinationCheck.getSelection());
			}
		});
		examinationCheck.setSelection(true);
		examinationCheck.setText("is Examination");
		new Label(group, SWT.NONE);

		sashForm = new SashForm(group, SWT.NONE);
		sashForm.setLayoutData(new GridData(SWT.FILL, SWT.BOTTOM, false, false,
				2, 1));

		final Shell shell = parent.getShell();
		pdfButton = new Button(sashForm, SWT.NONE);
		pdfButton.setText("Sheet to PDF");
		pdfButton.addSelectionListener(new SelectionAdapter() {
			@Override
			public void widgetSelected(SelectionEvent e) {

				FileDialog fd = new FileDialog(shell, SWT.SAVE);
				fd.setText("Save exercise sheet");
				String[] filterExt = { "*.pdf" };
				fd.setFilterExtensions(filterExt);
				String path = fd.open();
				String newFileName = selected.getLectureEvent().getLecture()
						.getName()
						+ " Blatt "
						+ selected.getNumber()
						+ " "
						+ selected.getLectureEvent().getSemesterString()
						+ String.valueOf(selected.getLectureEvent()
								.getSemester());
				PdfGenerator.generatePdf(selected, path, true, true);
				ExerciseSVN.SVNAdd(fd.getFileName(), newFileName);

				ExerciseSheetPDFDialog dialog = new ExerciseSheetPDFDialog(
						shell, path);

				dialog.open();

			}
		});

		solutionButton = new Button(sashForm, SWT.NONE);
		solutionButton.setText("Solutionsheet to PDF");
		solutionButton.addSelectionListener(new SelectionAdapter() {
			@Override
			public void widgetSelected(SelectionEvent e) {

				FileDialog fd = new FileDialog(shell, SWT.SAVE);
				fd.setText("Save solution sheet");
				String[] filterExt = { "*.pdf" };
				fd.setFilterExtensions(filterExt);
				String path = fd.open();
				String newFileName = selected.getLectureEvent().getLecture()
						.getName()
						+ " Blatt "
						+ selected.getNumber()
						+ " LÖSUNG "
						+ selected.getLectureEvent().getSemesterString()
						+ String.valueOf(selected.getLectureEvent()
								.getSemester());
				PdfGenerator.generatePdf(selected, path, true, false);
				ExerciseSVN.SVNAdd(fd.getFileName(), newFileName);

				ExerciseSheetPDFDialog dialog = new ExerciseSheetPDFDialog(
						shell, path);

				dialog.open();

			}
		});

		sashForm.setWeights(new int[] { 1, 1 });

		sashForm_1 = new SashForm(group, SWT.NONE);
		sashForm_1.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false,
				false, 2, 1));

		delPDF = new Button(sashForm_1, SWT.NONE);
		delPDF.addSelectionListener(new SelectionAdapter() {
			@Override
			public void widgetSelected(SelectionEvent e) {

				String path = selected.getLectureEvent().getLecture().getName()
						+ " Blatt "
						+ selected.getNumber()
						+ " "
						+ selected.getLectureEvent().getSemesterString()
						+ String.valueOf(selected.getLectureEvent()
								.getSemester());

				String pathSol = selected.getLectureEvent().getLecture()
						.getName()
						+ " Blatt "
						+ selected.getNumber()
						+ " LÖSUNG "
						+ selected.getLectureEvent().getSemesterString()
						+ String.valueOf(selected.getLectureEvent()
								.getSemester());

				File fileTest = new File(ExerciseSVN.SVNpath
						+ "exercisesheets/" + path.replaceAll(" ", "_")
						+ ".pdf");
				File fileTestSol = new File(ExerciseSVN.SVNpath
						+ "exercisesheets/" + pathSol.replaceAll(" ", "_")
						+ ".pdf");

				if (fileTest.exists() || fileTestSol.exists()) {
					ExerciseSheetPDFDeleteDialog dialog = new ExerciseSheetPDFDeleteDialog(
							shell, path, pathSol);
					dialog.open();
				} else {
					ExerciseSheetErrorDialog error = new ExerciseSheetErrorDialog(
							shell);
					error.open();
				}
			}
		});
		delPDF.setText("Remove PDF revision");

		previewButton = new Button(sashForm_1, SWT.NONE);
		previewButton.addSelectionListener(new SelectionAdapter() {
			@Override
			public void widgetSelected(SelectionEvent e) {
				PdfGenerator.generatePdf(selected, System
						.getProperty("java.io.tmpdir")
						+ "/tempPDFfileForPreview.pdf", false, true);
				try {
					Desktop d = Desktop.getDesktop();
					d.open(new File(System.getProperty("java.io.tmpdir")
							+ "/tempPDFfileForPreview.pdf"));

				} catch (IOException e1) {
					System.err.println(e1);
				}

			}
		});
		previewButton.setText("PDF preview");

		sashForm_1.setWeights(new int[] { 1, 1 });
		complexityText.addModifyListener(new ModifyListener() {
			public void modifyText(ModifyEvent e) {
				selected.setComplexityValue((int) Integer
						.parseInt(complexityText.getText()));

			}
		});
		sheetNumberText.addModifyListener(new ModifyListener() {
			public void modifyText(ModifyEvent e) {
				// TODO: Ueberpruefung, ob die Eingabe eine Zahl war
				selected.setNumber((int) Integer.parseInt(sheetNumberText
						.getText()));
				GUITreeView.getTree().getSelection()[0].setText("Sheet "
						+ sheetNumberText.getText());
			}
		});

		Composite keywordComposite = new Composite(this, SWT.NONE);
		keywordComposite.setLayout(new GridLayout(2, false));
		GridData gridData = new GridData(SWT.FILL, SWT.FILL, true, false, 2, 6);
		gridData.heightHint = 186;
		keywordComposite.setLayoutData(gridData);
		keywordsExtender = new KeywordsCompositeExtender(keywordComposite,
				CKeyword.EXERCISESHEET);
		gridData.heightHint = 306;

		Label currentExerciseLabel = new Label(this, SWT.NONE);
		currentExerciseLabel.setText("current Exercises:");

		generateButton = new Button(this, SWT.NONE);
		generateButton.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false,
				false, 1, 1));
		generateButton.addSelectionListener(new SelectionAdapter() {

			public void widgetSelected(SelectionEvent e) {
				ExerciseSheet.deleteDuplicates(selected.getId());
				generateSheet();
				refreshData();
				save();
			}
		});
		generateButton.setText("Generate Exercises");

		Label possibleExerciseLabel = new Label(this, SWT.NONE);
		possibleExerciseLabel.setText("possible Exercises:");
		new Label(this, SWT.NONE);

		currentExercisesTable = new Table(this, SWT.BORDER | SWT.FULL_SELECTION);
		currentExercisesTable.setLayoutData(new GridData(SWT.FILL, SWT.FILL,
				false, true, 2, 1));
		currentExercisesTable.setHeaderVisible(true);
		currentExercisesTable.setLinesVisible(true);

		currentTitle = new TableColumn(currentExercisesTable, SWT.NONE);
		currentTitle.setWidth(200);
		currentTitle.setText("Title");

		currentComplexity = new TableColumn(currentExercisesTable, SWT.NONE);
		currentComplexity.setResizable(false);
		currentComplexity.setWidth(20);
		currentComplexity.setText("Complexity");

		possibleExercisesTable = new Table(this, SWT.BORDER
				| SWT.FULL_SELECTION);
		possibleExercisesTable.setLayoutData(new GridData(SWT.FILL, SWT.FILL,
				true, true, 2, 1));
		possibleExercisesTable.setHeaderVisible(true);
		possibleExercisesTable.setLinesVisible(true);

		possibleTitle = new TableColumn(possibleExercisesTable, SWT.NONE);
		possibleTitle.setWidth(200);
		possibleTitle.setText("Title");

		possibleComplexity = new TableColumn(possibleExercisesTable, SWT.NONE);
		possibleComplexity.setResizable(false);
		possibleComplexity.setWidth(20);
		possibleComplexity.setText("Complexity");

		Transfer[] types = new Transfer[] { TextTransfer.getInstance() };
		int operations = DND.DROP_MOVE;

		final DragSource sourceCurrent = new DragSource(currentExercisesTable,
				operations);
		sourceCurrent.setTransfer(types);
		sourceCurrent.addDragListener(new ExerciseDragger(this,
				currentExercisesTable, true));

		DropTarget targetPossible = new DropTarget(possibleExercisesTable,
				operations);
		targetPossible.setTransfer(types);
		targetPossible.addDropListener(new ExerciseDropper(this, false));

		final DragSource sourcePossible = new DragSource(
				possibleExercisesTable, operations);
		sourcePossible.setTransfer(types);
		sourcePossible.addDragListener(new ExerciseDragger(this,
				possibleExercisesTable, false));

		DropTarget targetCurrent = new DropTarget(currentExercisesTable,
				operations);
		targetCurrent.setTransfer(types);
		targetCurrent.addDropListener(new ExerciseDropper(this, true));
	}

	public void load(ExerciseSheet exerciseSheet) {
		this.selected = exerciseSheet;
		refreshData();
	}

	public void save() {
		if (this.selected == null)
			return;
		selected.setNumber(Integer.parseInt(sheetNumberText.getText()));
		selected.setNumOfExercises(Integer.parseInt(numOfExercisesText
				.getText()));
		selected.save();
	}

	public void refreshData() {
		ExerciseSheet exerciseSheet = this.selected;
		keywordsExtender.load(exerciseSheet);
		sheetNumberText.setText("" + exerciseSheet.getNumber());
		complexityText.setText("" + exerciseSheet.getComplexityValue());
		numOfExercisesText.setText(String.valueOf(exerciseSheet
				.getNumOfExercises()));
		examinationCheck.setSelection(exerciseSheet.isExamination());
		lectureEventLabel.setText(exerciseSheet.getLectureEvent().getLecture()
				.getName()
				+ " "
				+ exerciseSheet.getLectureEvent().getSemesterString()
				+ exerciseSheet.getLectureEvent().getSemester());

		ArrayList<Exercise> exercises = exerciseSheet.getExercises();
		TableItem item;
		currentExercisesTable.removeAll();
		for (int i = 0; i < exercises.size(); i++) {
			item = new TableItem(currentExercisesTable, SWT.NONE);
			item.setData(exercises.get(i));
			item.setText(0, exercises.get(i).getTitle());
			item.setText(1, "" + exercises.get(i).getComplexity());
		}
		SheetGenerator possibleExercisesGenerator = new SheetGenerator(selected
				.getLectureEvent(), CKeyword.getKeywordsForModel(selected
				.getId(), CKeyword.EXERCISESHEET));

		ArrayList<Exercise> possibleExercises = possibleExercisesGenerator
				.getValidExercises();

		possibleExercises.removeAll(exercises);
		possibleExercisesTable.removeAll();
		for (Exercise exercise : possibleExercises) {
			item = new TableItem(possibleExercisesTable, SWT.NONE);
			item.setData(exercise);
			item.setText(0, exercise.getTitle());
			item.setText(1, "" + exercise.getComplexity());
		}

	}

	@Override
	protected void checkSubclass() {
		// Disable the check that prevents subclassing of SWT components
	}

	private void generateSheet() {
		ExerciseSheet exerciseSheet = selected;
		SheetGenerator generator = new SheetGenerator(exerciseSheet
				.getComplexityValue(), exerciseSheet.getLectureEvent(),
				CKeyword.getKeywordsForModel(exerciseSheet.getId(),
						CKeyword.EXERCISESHEET), Integer
						.parseInt(numOfExercisesText.getText()));
		ArrayList<Exercise> exerciseList = generator.generateExercises();
		for (int i = 0; i < exerciseList.size(); i++) {
			exerciseSheet.addExercise(exerciseList.get(i));
		}
		exerciseSheet.setExerciseMaxRevision(exerciseSheet.returnMaxRevision());

		exerciseSheet.save();
	}
}
