package com.temporaryteam.noticeditor.view;

import com.temporaryteam.noticeditor.model.NoticeTreeItem;

import javafx.event.EventHandler;
import javafx.scene.Node;
import javafx.scene.control.TextField;
import javafx.scene.control.TreeCell;
import javafx.scene.input.KeyCode;
import javafx.scene.input.KeyEvent;
import javafx.scene.paint.Color;
import javafx.scene.shape.Circle;

public class EditNoticeTreeCell extends TreeCell<String> {

	private TextField noticeName;

	@Override
	public void startEdit() {
		super.startEdit();
		if (noticeName == null) {
			createTextField();
		}
		setText(null);
		setGraphic(noticeName);
		noticeName.selectAll();
	}

	@Override
	public void cancelEdit() {
		super.cancelEdit();
		setText(getItem());
		setGraphic(getIcon());
	}

	@Override
	public void commitEdit(String str) {
		super.commitEdit(str);
		getNoticeTreeItem().setTitle(str);
	}

	@Override
	public void updateItem(String item, boolean empty) {
		super.updateItem(item, empty);
		if (empty) {
			setText(null);
			setGraphic(null);
		} else {
			if (isEditing()) {
				if (noticeName != null) {
					noticeName.setText(getString());
				}
				setText(null);
				setGraphic(noticeName);
			} else {
				setText(getString());
				setGraphic(getIcon());
			}
		}
	}

	private NoticeTreeItem getNoticeTreeItem() {
		return (NoticeTreeItem) getTreeItem();
	}

	private void createTextField() {
		noticeName = new TextField(getString());
		noticeName.setOnKeyReleased(new EventHandler<KeyEvent>() {
			@Override
			public void handle(KeyEvent t) {
				if (t.getCode() == KeyCode.ENTER) {
					commitEdit(noticeName.getText());
				} else if (t.getCode() == KeyCode.ESCAPE) {
					cancelEdit();
				}
			}
		});
	}

	private Node getIcon() {
		if (getNoticeTreeItem().isBranch()) {
			return null;
		} else {
			switch (getNoticeTreeItem().getStatus()) {
				case NoticeTreeItem.STATUS_IMPORTANT:
					return new Circle(5, Color.YELLOW);
				default:
					return new Circle(5, Color.AQUAMARINE);
			}
		}
	}

	/**
	 *
	 * @return selected item or empty string
	 */
	private String getString() {
		return ((getItem() == null) ? "" : getItem());
	}

}

@@ -434,16 +434,160 @@
 ing%3E %7B%0A%0A
+%09private final Circle CIRCLE_AQUAMARINE = new Circle(5, Color.AQUAMARINE);%0A%09private final Circle CIRCLE_YELLOW = new Circle(5, Color.YELLOW);%0A%09%0A
 %09private
@@ -1937,25 +1937,17 @@
 ull;%0A%09%09%7D
- else %7B%0A%09
+%0A
 %09%09switch
@@ -1983,17 +1983,16 @@
 us()) %7B%0A
-%09
 %09%09%09case 
@@ -2032,46 +2032,30 @@
 %09%09%09%09
-%09
 return 
-new Circle(5, Color.
+CIRCLE_
 YELLOW
-)
 ;%0A
-%09
 %09%09%09d
@@ -2070,36 +2070,22 @@
 %09%09%09%09
-%09
 return 
-new Circle(5, Color.
+CIRCLE_
 AQUA
@@ -2090,31 +2090,26 @@
 UAMARINE
-)
 ;%0A
-%09%09%09%7D%0A
 %09%09%7D%0A%09%7D%0A
+%09
 %0A%09/**%0A%09 

Fix memory leak while creating icon shape