package hsr.dsa.view.templates;

import java.io.IOException;
import java.util.Iterator;

import hsr.dsa.controller.ChatController;
import hsr.dsa.controller.ControllerManager;
import hsr.dsa.data.models.FriendRequest;
import hsr.dsa.utils.Observable;
import hsr.dsa.utils.ObservableList;
import hsr.dsa.utils.Observer;
import hsr.dsa.view.FXController;
import javafx.application.Platform;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.scene.Node;
import javafx.scene.Parent;
import javafx.scene.control.TextField;
import javafx.scene.layout.VBox;

@SuppressWarnings("restriction")
public class FriendRequestController implements FXTemplate<Void>, Observer {

	@FXML
	private TextField username;
	@FXML
	private VBox friendRequests;

	@Override
	public void setControler(FXController controller) {
	}

	@FXML
	public void initialize() throws IOException {
		ChatController chatController = ControllerManager.getChatController();
		ObservableList<FriendRequest> friendRequests = chatController.getProfile().getFriendRequests();
		friendRequests.addObserver(this);
		updateFriendRequests();
	}

	public void invite() {
		this.username.setDisable(true);
		new Thread() {
			public void run() {
				try {
					ChatController profileController = ControllerManager.getChatController();
					profileController.sendFriendRequest(username.getText());
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} finally {
					Platform.runLater(new Runnable() {
						public void run() {
							username.setDisable(false);
							username.setText("");
						}
					});
				}
			}
		}.start();

	}

	@SuppressWarnings("unchecked")
	private void updateFriendRequests() {
		try {
			ChatController chatController = ControllerManager.getChatController();
			ObservableList<FriendRequest> friendRequests = chatController.getProfile().getFriendRequests();
			
			Iterator<Node> i = this.friendRequests.getChildren().iterator();
			i.next();
			while(i.hasNext()) {
				i.next();
				i.remove();
			}
			
			for(FriendRequest friendRequest : friendRequests) {
				FXMLLoader loader = new FXMLLoader();
				Parent friend = (Parent) loader.load(getClass().getResourceAsStream("/fxml/chatWindow/templates/incomingFriendRequest.fxml"));
				FXTemplate<FriendRequest> templateControler = (FXTemplate<FriendRequest>) loader.getController();
				templateControler.setData(friendRequest);
				this.friendRequests.getChildren().add(friend);
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}

	@Override
	public void setData(Void data) {
	}

	@Override
	public void onChange(Observable observable) {
		Platform.runLater(() -> {
			this.updateFriendRequests();
		});
	}
}
