summaryrefslogtreecommitdiffstats
path: root/dozentenmodul/src/main/java/org/openslx/dozmod/gui/window/LectureDetailsWindow.java
blob: 33d5f164e8273f6ac385abca64607fe933dff1dd (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
package org.openslx.dozmod.gui.window;

import java.awt.Color;
import java.awt.Frame;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.IOException;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.swing.Action;
import javax.swing.DefaultComboBoxModel;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.text.BadLocationException;
import javax.swing.text.StyledEditorKit;
import javax.swing.text.html.HTML;
import javax.swing.text.html.HTMLDocument;

import org.apache.commons.codec.language.ColognePhonetic;
import org.apache.log4j.Logger;
import org.apache.thrift.TException;
import org.openslx.bwlp.thrift.iface.ImageDetailsRead;
import org.openslx.bwlp.thrift.iface.ImagePermissions;
import org.openslx.bwlp.thrift.iface.ImageSummaryRead;
import org.openslx.bwlp.thrift.iface.ImageVersionDetails;
import org.openslx.bwlp.thrift.iface.LecturePermissions;
import org.openslx.bwlp.thrift.iface.LectureRead;
import org.openslx.bwlp.thrift.iface.LectureWrite;
import org.openslx.bwlp.thrift.iface.UserInfo;
import org.openslx.dozmod.gui.Gui;
import org.openslx.dozmod.gui.MainWindow;
import org.openslx.dozmod.gui.changemonitor.AbstractControlWrapper;
import org.openslx.dozmod.gui.changemonitor.DialogChangeMonitor;
import org.openslx.dozmod.gui.changemonitor.DialogChangeMonitor.NotNullConstraint;
import org.openslx.dozmod.gui.changemonitor.DialogChangeMonitor.TextNotEmptyConstraint;
import org.openslx.dozmod.gui.changemonitor.DialogChangeMonitor.ValidationConstraint;
import org.openslx.dozmod.gui.configurator.NetrulesConfigurator.StateWrapper;
import org.openslx.dozmod.gui.configurator.StartupConfigurator.StartupSettings;
import org.openslx.dozmod.gui.helper.DateTimeHelper;
import org.openslx.dozmod.gui.helper.MessageType;
import org.openslx.dozmod.gui.helper.UiFeedback;
import org.openslx.dozmod.gui.window.UserListWindow.UserAddedCallback;
import org.openslx.dozmod.gui.window.layout.LectureDetailsWindowLayout;
import org.openslx.dozmod.permissions.ImagePerms;
import org.openslx.dozmod.permissions.LecturePerms;
import org.openslx.dozmod.thrift.ImageLocalDetailsActions;
import org.openslx.dozmod.thrift.Session;
import org.openslx.dozmod.thrift.ThriftActions;
import org.openslx.dozmod.thrift.ThriftActions.DownloadCallback;
import org.openslx.dozmod.thrift.ThriftActions.ImageMetaCallback;
import org.openslx.dozmod.thrift.ThriftActions.LectureMetaCallback;
import org.openslx.dozmod.thrift.ThriftError;
import org.openslx.dozmod.thrift.cache.UserCache;
import org.openslx.dozmod.util.FormatHelper;
import org.openslx.thrifthelper.Comparators;
import org.openslx.thrifthelper.ThriftManager;

/**
 * Window to display and edit the details of a lecture
 */
@SuppressWarnings("serial")
public class LectureDetailsWindow extends LectureDetailsWindowLayout implements UiFeedback {

	private static final Logger LOGGER = Logger.getLogger(LectureDetailsWindow.class);

	/**
	 * Self-reference
	 */
	private final LectureDetailsWindow me = this;

	/**
	 * Callback interface to refresh lecture list after changing lecture details
	 */
	public interface LectureUpdatedCallback {
		public void updated(boolean success);
	}

	/**
	 * Callback to be called when changing lecture details on the server
	 */
	private LectureUpdatedCallback callback = null;

	/**
	 * Lecture that this window shows the details of
	 */
	private LectureRead lecture = null;

	/**
	 * Action handler proxying thrift calls for image related operations
	 */
	private final ImageLocalDetailsActions actionHandler;

	/**
	 * Image, that the lecture is linked to.
	 */
	private ImageDetailsRead image = null;

	/**
	 * Per-User permissions of this lecture
	 */
	private Map<String, LecturePermissions> customPermissions;

	/**
	 * Did the user have admin rights due to default permissions?
	 */
	private boolean adminRightsFromDefaultPermissions;

	private final DialogChangeMonitor changeMonitor;

	private final AbstractControlWrapper<?> changeListenerPermissions;

	/**
	 * Constructor
	 * 
	 * @param modalParent parent of this popup window
	 * @param callback    function to be called when a lecture update occured
	 */
	public LectureDetailsWindow(Frame modalParent, LectureUpdatedCallback callback) {
		super(modalParent);

		// save callback
		this.callback = callback;

		setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);

		// Set up change monitor
		changeMonitor = new DialogChangeMonitor(new DialogChangeMonitor.Callback() {
			@Override
			public void validityChanged(String errorMessage) {
				lblError.setText(errorMessage);
				btnSaveChanges.setEnabled(changeMonitor.isValid() && changeMonitor.wasEverModified());
				LOGGER.info("Valid: " + changeMonitor.isValid());
			}

			@Override
			public void modificationChanged() {
				btnSaveChanges.setEnabled(changeMonitor.isValid() && changeMonitor.wasEverModified());
				LOGGER.info("Changed: " + changeMonitor.isCurrentlyModified());
			}
		});

		// Add controls to change monitor
		changeMonitor.addFixedCombo(cboVersions, Comparators.imageVersionDetails)
				.addConstraint(new DialogChangeMonitor.ValidationConstraint<ImageVersionDetails>() {
					public String checkStateValid(ImageVersionDetails userInput) {
						if (userInput != null && userInput.isValid)
							return null;
						return "Keine/Ungültige VM-Version ausgewählt";
					}
				});
		// Create constraint for date start/end
		final Date maxValidity;
		Calendar c = Calendar.getInstance();
		c.add(Calendar.DAY_OF_MONTH, Session.getSatelliteConfig().maxLectureValidityDays);
		maxValidity = c.getTime();
		ValidationConstraint<Object> dateRangeValidator = new DialogChangeMonitor.ValidationConstraint<Object>() {
			public String checkStateValid(Object ignored) {
				Date start = DateTimeHelper.getDateFrom(dtpStartDate, spnStartTime);
				Date end = DateTimeHelper.getDateFrom(dtpEndDate, spnEndTime);
				if (!end.after(start))
					return "Enddatum darf nicht vor dem Startdatum liegen";
				if (end.after(maxValidity))
					return "Enddatum liegt nach dem " + FormatHelper.shortDate(maxValidity);
				return null;
			}
		};
		changeMonitor.add(chkAutoUpdate);
		changeMonitor.add(chkIsExam);
		changeMonitor.add(chkHasInternetAccess);
		changeMonitor.add(chkHasUsbAccess);
		changeMonitor.add(chkIsActive);
		changeMonitor.add(chkCustomPermAdmin);
		changeMonitor.add(chkCustomPermEdit);
		changeMonitor.add(txtTitle)
				.addConstraint(new TextNotEmptyConstraint("Veranstaltungsname darf nicht leer sein"));
		changeMonitor.add(txtDescription)
				.addConstraint(new TextNotEmptyConstraint("Beschreibung darf nicht leer sein"));
		changeMonitor.add(dtpEndDate).addConstraint(dateRangeValidator);
		changeMonitor.add(dtpStartDate).addConstraint(dateRangeValidator);
		changeMonitor.add(spnEndTime).addConstraint(dateRangeValidator);
		changeMonitor.add(spnStartTime).addConstraint(dateRangeValidator);
		changeMonitor.add(ctlNetrulesConfigurator)
				.addConstraint(new NotNullConstraint<StateWrapper>("Fehlerhafte Netzwerkregeln"));
		changeListenerPermissions = changeMonitor.add(ctlPermissionManager);
		ctlLocationSelector.addToChangeMonitor(changeMonitor);
		ctlRunscriptConfigurator.addToChangeMonitor(changeMonitor);
		ctlNetshareConfigurator.addToChangeMonitor(changeMonitor);
		ctlLdapFilterConfigurator.addToChangeMonitor(changeMonitor);
		// TODO: LDAP/NetShare: Having uncommitted changes in the input fields should be
		// handled too
		// End change monitor

		addWindowListener(new WindowAdapter() {
			@Override
			public void windowClosing(WindowEvent e) {
				safeClose();
			}
		});

		actionHandler = new ImageLocalDetailsActions(JOptionPane.getFrameForComponent(LectureDetailsWindow.this));

		btnLinkImage.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				final ImageSummaryRead newImage = LectureChangeImage.open(LectureDetailsWindow.this, changeMonitor);
				if (newImage == null)
					return;
				final ImageMetaCallback callback = new ImageMetaCallback() {
					@Override
					public void fetchedImageDetails(ImageDetailsRead imageDetails,
							Map<String, ImagePermissions> permissions) {
						if (imageDetails == null) {
							return;
						}
						synchronized (me) {
							image = imageDetails;
						}
						lecture.imageBaseId = newImage.imageBaseId;
						lecture.imageVersionId = newImage.latestVersionId;
						fillVersionsCombo();
						cboVersions.setEnabled(false);
						chkAutoUpdate.setSelected(true);
						txtImageName.setText(newImage.getImageName());
					}
				};
				actionHandler.getImageDetails(newImage.imageBaseId, callback);
			}
		});

		btnClose.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				safeClose();
			}
		});
		btnDownloadImage.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				performImageDownload();
			}
		});
		chkAutoUpdate.addItemListener(new ItemListener() {
			@Override
			public void itemStateChanged(ItemEvent e) {
				cboVersions.setEnabled(!chkAutoUpdate.isSelected());
			}
		});
		btnChangeOwner.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				UserListWindow.open(me, new UserAddedCallback() {
					@Override
					public void userAdded(UserInfo user, UserListWindow window) {
						window.dispose();
						if (Gui.showMessageBox(me,
								"Sind Sie sicher, dass sie die Besitzerrechte an "
										+ "einen anderen Account übertragen wollen?",
								MessageType.QUESTION_YESNO, LOGGER, null))
							setLectureOwner(user);
					}
				}, "Besitzer festlegen", lecture.ownerId);
			}
		});

		cbTxtSize.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				int size = Integer.parseInt((String) cbTxtSize.getSelectedItem());
				Action act = new StyledEditorKit.FontSizeAction(String.valueOf(size),size);
				act.actionPerformed(new ActionEvent(act,ActionEvent.ACTION_PERFORMED, 
					(String)act.getValue(Action.ACTION_COMMAND_KEY)));
			}
		});

		cbTxtColor.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				String color = (String) cbTxtColor.getSelectedItem();
				Action act = null;

				switch(color) {
					case "Black":
						act = new StyledEditorKit.ForegroundAction("Black", Color.black);
						break;
					case "Blue":
						act = new StyledEditorKit.ForegroundAction("Blue", Color.blue);
						break;
					case "Yellow":
						act = new StyledEditorKit.ForegroundAction("Yellow", Color.yellow);
						break;
					case "Red":
						act = new StyledEditorKit.ForegroundAction("Red", Color.red);
						break;
					case "Green":
						act = new StyledEditorKit.ForegroundAction("Green", Color.green);
						break;
				}

				act.actionPerformed(new ActionEvent(act,ActionEvent.ACTION_PERFORMED,
						(String)act.getValue(Action.ACTION_COMMAND_KEY)));
			}
		});


		btnWysiwyg.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				String tmp = txtDescription.getText();
				if (txtDescription.getContentType().equals("text/html")) {
					txtDescription.setContentType("text/plain");
					txtDescription.setText(tmp);
					btnWysiwyg.setText("Wysiwyg");
					if (ImagePerms.canEdit(image) || ImagePerms.canAdmin(image)) {
						btnSaveChanges.setEnabled(true);
					}

					btnBold.setEnabled(false);
					btnUnderline.setEnabled(false);
					btnItalic.setEnabled(false);
					cbTxtColor.setEnabled(false);
					cbTxtSize.setEnabled(false);
				} else {
					txtDescription.setContentType("text/html");
					txtDescription.setText(tmp);
					btnWysiwyg.setText("Html");

					btnBold.setEnabled(true);
					btnUnderline.setEnabled(true);
					btnItalic.setEnabled(true);
					cbTxtColor.setEnabled(true);
					cbTxtSize.setEnabled(true);
				}
			}
		});

		txtDescription.addKeyListener(new KeyListener() {
			@Override
			public void keyPressed(KeyEvent e) {
			}

			@Override
			public void keyTyped(KeyEvent e) {
			}

			@Override
			public void keyReleased(KeyEvent e) {
				if (e.getKeyCode() == KeyEvent.VK_ENTER && txtDescription.getContentType().equals("text/html")) {
					try {
						kit.insertHTML((HTMLDocument) txtDescription.getDocument(), txtDescription.getCaretPosition(),
								"<br>", 0, 0, HTML.Tag.BR);
						txtDescription.setCaretPosition(txtDescription.getCaretPosition()); // This moves caret to next
																							// line
					} catch (BadLocationException | IOException ex) {
						ex.printStackTrace();
					}
				}
			}
		});


		// Update default permissions in the permission manager immediately, so it
		// affects
		// newly added users
		final ItemListener updateDefaultPermissionListener = new ItemListener() {
			@Override
			public void itemStateChanged(ItemEvent e) {
				if (e.getSource() == chkCustomPermAdmin) {
					lecture.defaultPermissions.admin = chkCustomPermAdmin.isSelected();
				} else {
					lecture.defaultPermissions.edit = chkCustomPermEdit.isSelected();
				}
			}
		};
		chkCustomPermAdmin.addItemListener(updateDefaultPermissionListener);
		chkCustomPermEdit.addItemListener(updateDefaultPermissionListener);

		// last step, the save button
		btnSaveChanges.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				saveChanges();
			}
		});
		// disable save button
		btnSaveChanges.setEnabled(false);
		// wait for the image to be loaded before (potentially) enabling fields
		toggleEditable(false);
	}

	/**
	 * Sets the lecture to show the details of by setting the 'lecture' and 'image'
	 * members to its metadata. This method will fetch the information from the sat
	 * 
	 * @param lectureId the id of the lecture to be displayed
	 */
	public void setLecture(final String lectureId) {
		ThriftActions.getLectureAndImageDetails(JOptionPane.getFrameForComponent(me), lectureId,
				new LectureMetaCallback() {
					@Override
					public void fetchedLectureAndImageDetails(LectureRead lectureDetails,
							ImageDetailsRead imageDetails) {
						synchronized (me) {
							lecture = lectureDetails;
							image = imageDetails;
							if (lecture != null) {
								customPermissions = ThriftActions
										.getLecturePermissions(JOptionPane.getFrameForComponent(me), lecture.lectureId);
							}
							fillDetails();
						}
					}
				});
	}

	/**
	 * Internal callback function when we received the lecture's details from the
	 * server
	 */
	private void fillDetails() {
		if (lecture == null) {
			txtTitle.setText("-");
			lblTitleInfo.setText("-");
			toggleEditable(false);
			return;
		}

		if (image == null) {
			txtImageName.setText("-");
			lblImageNameInfo.setText("-");
		} else {
			txtImageName.setText(image.getImageName());
			lblImageNameInfo.setText(image.getImageName());
		}
		// init permission info
		adminRightsFromDefaultPermissions = lecture.defaultPermissions.admin;
		ctlPermissionManager.initPanel(customPermissions, lecture.defaultPermissions, lecture.ownerId);
		chkCustomPermAdmin.setSelected(lecture.defaultPermissions.admin);
		chkCustomPermEdit.setSelected(lecture.defaultPermissions.edit);
		// init location info
		ctlLocationSelector.setOnlyInSelection(lecture.limitToLocations);
		ctlLocationSelector.setSelectedLocationsAsIds(lecture.locationIds);

		// init advanced info
		ctlRunscriptConfigurator.setState(lecture);
		ctlNetshareConfigurator.setState(lecture.networkShares, lecture.presetNetworkShares);
		ctlLdapFilterConfigurator.setState(lecture.ldapFilters, lecture.presetLdapFilters);
		ctlNetrulesConfigurator.setState(lecture);

		txtTitle.setText(lecture.getLectureName());
		lblTitleInfo.setText(lecture.getLectureName());
		txtDescription.setText(lecture.getDescription());
		lblOwner.setUser(UserCache.find(lecture.getOwnerId()));
		lblOwnerInfo.setUser(UserCache.find(lecture.getOwnerId()));
		lblUpdater.setUser(UserCache.find(lecture.getUpdaterId()));
		lblCreateTime.setText(FormatHelper.longDate(lecture.getCreateTime()));
		lblUpdateTime.setText(FormatHelper.longDate(lecture.getUpdateTime()));
		lblStartTime.setText(FormatHelper.longDate(lecture.getStartTime()));
		lblEndTime.setText(FormatHelper.longDate(lecture.getEndTime()));
		txtId.setText(lecture.getLectureId());

		chkIsActive.setSelected(lecture.isEnabled);
		chkHasInternetAccess.setSelected(lecture.hasInternetAccess);
		chkHasUsbAccess.setSelected(lecture.hasUsbAccess);
		chkIsExam.setSelected(lecture.isExam);
		chkAutoUpdate.setSelected(lecture.autoUpdate);
		cboVersions.setEnabled(!lecture.autoUpdate);

		lblUseCount.setText(Integer.toString(lecture.useCount));
		fillVersionsCombo();

		Calendar startCal = Calendar.getInstance();
		startCal.setTime(new Date(lecture.getStartTime() * 1000l));
		dtpStartDate.getModel().setDate(startCal.get(Calendar.YEAR), startCal.get(Calendar.MONTH),
				startCal.get(Calendar.DATE));
		spnStartTime.getModel().setValue(startCal.getTime());

		Calendar endCal = Calendar.getInstance();
		endCal.setTime(new Date(lecture.getEndTime() * 1000l));
		dtpEndDate.getModel().setDate(endCal.get(Calendar.YEAR), endCal.get(Calendar.MONTH), endCal.get(Calendar.DATE));
		spnEndTime.getModel().setValue(endCal.getTime());

		// now enable the tabs the user can see given its permissions
		toggleEditable(true);
		// and always switch to the "About" tab
		pnlTabs.setSelectedIndex(pnlTabs.indexOfTab("Übersicht"));
		setVisible(true);
		changeMonitor.reset();
	}

	/**
	 * Helper to fill the combobox with the versions of the image. The list will be
	 * sorted by creation timestamp
	 */
	private void fillVersionsCombo() {
		List<ImageVersionDetails> versions;
		if (image == null) {
			versions = new ArrayList<>(0);
		} else {
			versions = image.getVersions();
		}
		// version combo
		for (Iterator<ImageVersionDetails> it = versions.iterator(); it.hasNext();) {
			ImageVersionDetails version = it.next();
			if (!version.isValid && !lecture.imageVersionId.equals(version.versionId)) {
				it.remove();
			}
		}

		// sort versions by createtime
		Collections.sort(versions, new Comparator<ImageVersionDetails>() {
			public int compare(ImageVersionDetails o1, ImageVersionDetails o2) {
				return -Long.compare(o1.getCreateTime(), o2.getCreateTime());
			}
		});

		cboVersions.setModel(new DefaultComboBoxModel<ImageVersionDetails>(
				versions.toArray(new ImageVersionDetails[versions.size()])));
		cboVersions.setSelectedIndex(-1); // To make the change monitor happy
		cboVersions.setSelectedItem(
				new ImageVersionDetails(lecture.getImageVersionId(), 0, 0, 0, null, true, true, true, null));
	}

	/**
	 * Sets the lecture's owner to the given user
	 * 
	 * @param user UserInfo representation of the new owner
	 */
	private void setLectureOwner(final UserInfo user) {
		if (!ThriftActions.setLectureOwner(JOptionPane.getFrameForComponent(this), lecture.getLectureId(), user)) {
			return;
		}
		// success
		Gui.showMessageBox(me, "Besitzrechte übertragen an " + FormatHelper.userName(user), MessageType.INFO, null,
				null);
		toggleEditable(false);
		String lectureId = lecture.getLectureId();
		synchronized (me) {
			image = null;
			lecture = null;
		}
		setLecture(lectureId);
	}

	/**
	 * Triggers the download of the currently used image version of the lecture
	 */
	private void performImageDownload() {
		if (image == null) {
			Gui.showMessageBox(this, "VM ungültig.", MessageType.ERROR, null, null);
			return;
		}
		btnDownloadImage.setEnabled(false);
		long versionSize = 0;
		for (ImageVersionDetails version : image.versions) {
			if (version.versionId.equals(lecture.imageVersionId)) {
				if (!version.isValid) {
					Gui.showMessageBox(this, "Ungültige VM-Version gewählt", MessageType.ERROR, null, null);
					return;
				}
				versionSize = version.fileSize;
				break;
			}
		}
		if (versionSize == 0) {
			Gui.showMessageBox(this, "Fehler bei der Abfrage der Größe des VM-Abbildes.", MessageType.ERROR, null,
					null);
			return;
		}
		ThriftActions.initDownload(JOptionPane.getFrameForComponent(this), lecture.imageVersionId, image.imageName,
				image.virtId, image.osId, versionSize, new DownloadCallback() {
					@Override
					public void downloadInitialized(boolean success) {
						if (!success) {
							Gui.asyncExec(new Runnable() {
								@Override
								public void run() {
									btnDownloadImage.setEnabled(true);
								}
							});
						}
					}
				});
	}

	/**
	 * Triggers the saving of the changes of this lecture And inform the callback
	 * function about the outcome
	 */
	private void saveChanges() {
		boolean saved = saveChangesInternal();
		callback.updated(saved);
		if (saved) {
			dispose();
		} else {
			btnSaveChanges.setEnabled(true);
		}
	}

	/**
	 * Internal helper actually saving the changes to the satellite
	 *
	 * @return true if saving succeeded, false otherwise.
	 */
	private boolean saveChangesInternal() {
		long startTime = DateTimeHelper.getDateFrom(dtpStartDate, spnStartTime).getTime() / 1000L;
		long endTime = DateTimeHelper.getDateFrom(dtpEndDate, spnEndTime).getTime() / 1000L;
		if (!isPeriodValid(startTime, endTime, true))
			return false;

		// check, whether autoupdate is selected and choose version accordingly
		if (image != null) {
			lecture.imageVersionId = chkAutoUpdate.isSelected() ? image.latestVersionId
					: cboVersions.getItemAt(cboVersions.getSelectedIndex()).versionId;
		}

		// Special case similar to ImageDetailsWindow:if the user had admin rights
		// through default permissions, first save custom permissions.
		if (adminRightsFromDefaultPermissions && changeListenerPermissions.isCurrentlyChanged()) {
			if (!saveCustomPermissions()) {
				return false;
			}
			changeListenerPermissions.reset();
		}
		// first build the LectureWrite from the GUI fields
		StartupSettings startupSettings = ctlRunscriptConfigurator.getState();
		final LectureWrite metadata = new LectureWrite(txtTitle.getText(), txtDescription.getText(),
				lecture.getImageVersionId(), chkAutoUpdate.isSelected(), chkIsActive.isSelected(), startTime, endTime,
				startupSettings.serializeItems(), null, chkIsExam.isSelected(), chkHasInternetAccess.isSelected(),
				lecture.getDefaultPermissions(), ctlLocationSelector.getSelectedLocationsAsIds(),
				ctlLocationSelector.getOnlyInSelection(),
				// TODO limitOnlyToAllowedUsers, default to false for now
				false, chkHasUsbAccess.isSelected());
		StateWrapper netrules = ctlNetrulesConfigurator.getState();
		metadata.setNetworkExceptions(netrules.customRules);
		metadata.setPresetNetworkExceptionIds(netrules.selectedPresets);
		metadata.setNetworkShares(ctlNetshareConfigurator.getState());
		metadata.setLdapFilters(ctlLdapFilterConfigurator.getState());
		metadata.setPresetScriptIds(startupSettings.selectedScripts);

		// now trigger the actual action
		try {
			ThriftManager.getSatClient().updateLecture(Session.getSatelliteToken(), lecture.getLectureId(), metadata);
			LOGGER.info("Successfully saved new metadata");
		} catch (TException e) {
			ThriftError.showMessage(JOptionPane.getFrameForComponent(this), LOGGER, e,
					"Fehler beim Speichern der Veranstaltung!");
			return false;
		}

		if (changeListenerPermissions.isCurrentlyChanged()) {
			if (!saveCustomPermissions()) {
				return false;
			}
		}
		changeMonitor.reset();
		return true;
	}

	/**
	 * Helper to save custom user permissions.
	 *
	 * @return true if successfully saved, false otherwise.
	 */
	private boolean saveCustomPermissions() {
		try {
			ThriftManager.getSatClient().writeLecturePermissions(Session.getSatelliteToken(), lecture.lectureId,
					ctlPermissionManager.getPermissions());
			LOGGER.info("Successfully saved custom permissions");
			return true;
		} catch (TException e) {
			ThriftError.showMessage(JOptionPane.getFrameForComponent(this), LOGGER, e,
					"Fehler beim Übertragen der Berechtigungen!");
		}
		return false;
	}

	/**
	 * Checks if the given start and end date represent a valid time period. This is
	 * the case, if start < end and if current time < end
	 * 
	 * @param start    date of the period to check
	 * @param end      date of the period to check
	 * @param feedback true if the user should be shown feedback, false otherwise
	 * @return true if the period is valid, false otherwise
	 */
	private boolean isPeriodValid(long start, long end, boolean feedback) {
		if (start <= 0 || end <= 0)
			return false;
		// analyse time stuff to see if its valid
		if (end > start)
			return true;
		String msg = "Start der Veranstaltung ist nach dem Enddatum!";
		if (feedback) {
			Gui.showMessageBox(me, msg, MessageType.ERROR, LOGGER, null);
		}
		lblError.setText(msg);
		return false;
	}

	/**
	 * Enables/Disables the tabs based on the given flag 'editable'.
	 *
	 * @param editable when true, will enable the tabs if the user is allowed to see
	 *                 them. If false, this will disable all tabs but the first tab
	 *                 "About".
	 */
	protected void toggleEditable(boolean editable) {
		// if we don't have a lecture and an image set, just disable
		editable &= (LecturePerms.canEdit(lecture));
		// enable the standard tabs that are always enabled
		setTabEnabled(pnlTabGeneral, editable);
		setTabEnabled(pnlTabPermissions, editable && LecturePerms.canAdmin(lecture));
		// enable the other tabs that might have been added to the panel (depends on API
		// version)
		setTabEnabled(pnlTabRestrictions, editable);
		setTabEnabled(pnlTabLocations, editable);
		setTabEnabled(pnlTabRunscript, editable);
		setTabEnabled(pnlTabNetshare, editable);
		setTabEnabled(pnlTabLdapFilter, editable);
		setTabEnabled(pnlTabNetrules, editable);
		btnChangeOwner.setEnabled(LecturePerms.canAdmin(lecture));
		btnDownloadImage.setEnabled(ImagePerms.canDownload(image));
	}

	private void setTabEnabled(JPanel tab, boolean editable) {
		int index = pnlTabs.indexOfComponent(tab);
		if (index == -1) // Check if tab exists -- we don't add some, depending on server version
			return;
		pnlTabs.setEnabledAt(index, editable);
	}

	/**
	 * Opens a new LectureDetailsWindow showing the details of the lecture with ID =
	 * lectureId
	 * 
	 * @param modalParent parent of this window
	 * @param lectureId   id of the lecture to set the details of
	 */
	public static void open(Frame modalParent, String lectureId, LectureUpdatedCallback callback) {
		LectureDetailsWindow win = new LectureDetailsWindow(modalParent, callback);
		win.setLecture(lectureId);
		win.setVisible(true);
	}

	@SuppressWarnings("deprecation")
	@Override
	public void show() {
		if (!isVisible()) {
			pack();
			MainWindow.centerShell(this);
		}
		super.show();
	}

	/*
	 * *****************************************************************************
	 * **
	 * 
	 * UIFeedback implementation
	 *
	 ********************************************************************************/
	@Override
	public boolean wantConfirmQuit() {
		return changeMonitor.isCurrentlyModified();
	}

	@Override
	public void escapePressed() {
		// Also ask if applicable
		safeClose();
	}

	/*
	 * Safe close helper: checks if we have unsaved work and prompt the user for
	 * confirmation if so
	 */
	private void safeClose() {
		if (changeMonitor.isCurrentlyModified() && !Gui.showMessageBox(me,
				"Änderungen werden verworfen, wollen Sie wirklich schließen?", MessageType.QUESTION_YESNO, null, null))
			return;
		synchronized (me) {
			lecture = null;
			image = null;
		}
		dispose();
	}
}