package szakdolgozat.client.ui;

import java.util.Date;

import szakdolgozat.client.UI;

import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.i18n.client.DateTimeFormat;
import com.google.gwt.user.client.History;
import com.google.gwt.user.client.Timer;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.HasHorizontalAlignment;
import com.google.gwt.user.client.ui.HasVerticalAlignment;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.Label;

public class InfoPanel extends Composite {

	private static Label userNameLabel;
	private static Button logoutButton;
	private static Timer t;

	public InfoPanel() {

		HorizontalPanel infoPanel = new HorizontalPanel();
		initWidget(infoPanel);
		infoPanel.setSpacing(10);
		infoPanel.setVerticalAlignment(HasVerticalAlignment.ALIGN_MIDDLE);
		infoPanel.setHorizontalAlignment(HasHorizontalAlignment.ALIGN_CENTER);

		userNameLabel = new Label("");
		userNameLabel
				.setHorizontalAlignment(HasHorizontalAlignment.ALIGN_CENTER);
		infoPanel.add(userNameLabel);

		logoutButton = new Button("New button");
		logoutButton.setStyleName("gwt-PushButton-up");
		logoutButton.setText("Kilépés");
		infoPanel.add(logoutButton);
		infoPanel.setCellVerticalAlignment(logoutButton,
				HasVerticalAlignment.ALIGN_MIDDLE);
		infoPanel.setCellHorizontalAlignment(logoutButton,
				HasHorizontalAlignment.ALIGN_CENTER);
		logoutButton.setSize("", "20");
		logoutButton.addClickHandler(new ClickHandler() {

			@Override
			public void onClick(ClickEvent event) {
				logout();
			}
		});
	}

	public void setInfoPanelText(String info) {
		userNameLabel.setText(info);
	}

	public static void logout() {

		UI.servicesHandler.logoutUser(UI.currentUser,
				new AsyncCallback<Void>() {

					@Override
					public void onFailure(Throwable caught) {
						// TODO Auto-generated method stub

					}

					@Override
					public void onSuccess(Void result) {
						History.newItem("login");
						t.cancel();
						UI.currentUser = null;
					}
				});

	}

	public void init() {
		final Date loginTime = new Date();
		final String userName = UI.currentUser.getUsername();
		
		t = new Timer() {

			@Override
			public void run() {
				Date now = new Date();
				long diff = now.getTime() - loginTime.getTime() - 3600000; // 1 órával miért több?
				setInfoPanelText("Üdv kedves "
						+ userName
						+ "! ("
						+ DateTimeFormat.getFormat("HH:mm").format(
								new Date(diff)) + ")");
				this.scheduleRepeating(60000);
			}
		};
		t.scheduleRepeating(10);		
	}
}
