package hsr.dsa.view.templates;

import java.io.IOException;

import hsr.dsa.controller.ChatController;
import hsr.dsa.controller.ControllerManager;
import hsr.dsa.data.models.Group;
import hsr.dsa.data.models.User;
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.Parent;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
import javafx.scene.layout.VBox;

@SuppressWarnings("restriction")
public class GroupInvitationController implements FXTemplate<Group>, Observer {
	private Group group;
	private ObservableList<User> members;

	@FXML
	private Label groupname;
	@FXML
	private TextField username;
	@FXML
	private VBox groupInvitationRequests;

	@Override
	public void setControler(FXController controller) {
	}

	@FXML
	public void initialize() throws IOException {

	}

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

	@Override
	public void setData(Group group) {
		this.group = group;
		this.members = group.getMembers();
		this.members.addObserver(this);
		if(this.groupname != null) {
			this.groupname.setText("Group: " + group.getName());
		}
		this.updateMembers();
	}

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

	@SuppressWarnings("unchecked")
	private void updateMembers() {
		this.groupInvitationRequests.getChildren().retainAll(this.groupInvitationRequests.getChildren().get(0));
		try {
			for (User user : this.members) {
				FXMLLoader loader = new FXMLLoader();
				Parent friend = (Parent) loader
						.load(getClass().getResourceAsStream("/fxml/chatWindow/templates/groupMember.fxml"));
				FXTemplate<User> templateControler = (FXTemplate<User>) loader.getController();
				templateControler.setData(user);
				this.groupInvitationRequests.getChildren().add(friend);
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
