package szakdolgozat.client.ui;

import java.util.ArrayList;

import szakdolgozat.client.Services;
import szakdolgozat.client.ServicesAsync;
import szakdolgozat.client.UI;
import szakdolgozat.shared.User;
import szakdolgozat.shared.UserStats;

import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.i18n.client.NumberFormat;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.rpc.ServiceDefTarget;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.CheckBox;
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;
import com.google.gwt.user.client.ui.VerticalPanel;
import com.smartgwt.client.types.Alignment;
import com.smartgwt.client.types.ListGridFieldType;
import com.smartgwt.client.types.SelectionStyle;
import com.smartgwt.client.widgets.grid.CellFormatter;
import com.smartgwt.client.widgets.grid.ListGrid;
import com.smartgwt.client.widgets.grid.ListGridField;
import com.smartgwt.client.widgets.grid.ListGridRecord;
import com.smartgwt.client.widgets.grid.events.SelectionChangedHandler;
import com.smartgwt.client.widgets.grid.events.SelectionEvent;

public class UserListWindow extends Composite {
	public ArrayList<User> loggedinUsers = new ArrayList<User>();
	public ArrayList<UserStats> userStats = new ArrayList<UserStats>();
	private VerticalPanel verticalPanel;
	// private ScrollPanel scrollPanel;
	// private FlexTable userListflexTable;
	private HorizontalPanel horizontalPanel;
	private Label lblFelkrsekAutomatikusElutastsa;
	public CheckBox refuseProposalsCheckBox;
	public ListGrid userListGrid;
	private HorizontalPanel horizontalPanel_1;
	private Label selectedPlayerName;
	private Button selectedPlayerStats;
	private Button gameStarterButton;

	public UserListWindow() {

		verticalPanel = new VerticalPanel();
		// verticalPanel.setBorderWidth(1);
		verticalPanel.setVerticalAlignment(HasVerticalAlignment.ALIGN_MIDDLE);
		verticalPanel
				.setHorizontalAlignment(HasHorizontalAlignment.ALIGN_CENTER);
		initWidget(verticalPanel);
		verticalPanel.setSpacing(2);

		Label lblBejelentkezettFelhasznlk = new Label(
				"Bejelentkezett felhasználók");
		lblBejelentkezettFelhasznlk.setStyleName("gwt-blueLabel");
		verticalPanel.add(lblBejelentkezettFelhasznlk);

		horizontalPanel = new HorizontalPanel();
		horizontalPanel.setVerticalAlignment(HasVerticalAlignment.ALIGN_MIDDLE);
		horizontalPanel
				.setHorizontalAlignment(HasHorizontalAlignment.ALIGN_CENTER);
		horizontalPanel.setSpacing(2);
		verticalPanel.add(horizontalPanel);

		lblFelkrsekAutomatikusElutastsa = new Label(
				"Felkérések automatikus elutasítása");
		horizontalPanel.add(lblFelkrsekAutomatikusElutastsa);

		refuseProposalsCheckBox = new CheckBox("");
		horizontalPanel.add(refuseProposalsCheckBox);

		/*
		 * scrollPanel = new ScrollPanel(); //verticalPanel.add(scrollPanel);
		 * scrollPanel.setWidth("454px");
		 * verticalPanel.setCellVerticalAlignment(scrollPanel,
		 * HasVerticalAlignment.ALIGN_MIDDLE);
		 * verticalPanel.setCellHorizontalAlignment(scrollPanel,
		 * HasHorizontalAlignment.ALIGN_CENTER);
		 * 
		 * userListflexTable = new FlexTable();
		 * userListflexTable.setCellSpacing(1);
		 * userListflexTable.setStyleName("gwt-FlexTable-blue");
		 * userListflexTable.setBorderWidth(2);
		 * scrollPanel.setWidget(userListflexTable);
		 * userListflexTable.setSize("436px", "100%");
		 * 
		 * userListflexTable.setWidget(0, 0, new Label("Játékosnév"));
		 * userListflexTable.setWidget(0, 1, new Label("Játékok száma"));
		 * userListflexTable.setWidget(0, 2, new Label("Nyerési arány"));
		 * userListflexTable.setWidget(0, 3, new Label("Új játék"));
		 * 
		 * for (int i = 0; i <= 3; i++) {
		 * 
		 * userListflexTable.getCellFormatter().setHorizontalAlignment(0, i,
		 * HasHorizontalAlignment.ALIGN_CENTER);
		 * userListflexTable.getCellFormatter().setVerticalAlignment(0, i,
		 * HasVerticalAlignment.ALIGN_MIDDLE); }
		 */

		horizontalPanel_1 = new HorizontalPanel();
		horizontalPanel_1
				.setVerticalAlignment(HasVerticalAlignment.ALIGN_MIDDLE);
		horizontalPanel_1
				.setHorizontalAlignment(HasHorizontalAlignment.ALIGN_CENTER);
		horizontalPanel_1.setSpacing(3);
		verticalPanel.add(horizontalPanel_1);

		selectedPlayerStats = new Button("");
		selectedPlayerStats.setEnabled(false);
		selectedPlayerStats.setText("Játékos statisztikái");
		horizontalPanel_1.add(selectedPlayerStats);

		selectedPlayerName = new Label("");
		horizontalPanel_1.add(selectedPlayerName);

		gameStarterButton = new Button("New button");
		gameStarterButton.setEnabled(false);
		gameStarterButton.setText("Játék indítása ellene");
		horizontalPanel_1.add(gameStarterButton);
		userListGrid = new ListGrid() {
			@Override
			protected String getCellCSSText(ListGridRecord record, int rowNum,
					int colNum) {
				if (getFieldName(colNum).equals("arány")) {
					UserListRecord countryRecord = (UserListRecord) record;
					if (countryRecord.getGamesWon() < 0.2) {
						return "font-weight:bold; color:#FF0000;";
					} else if (countryRecord.getGamesWon() < 0.4) {
						return "font-weight:bold; color:#FF8000;";
					} else if (countryRecord.getGamesWon() < 0.6) {
						return "font-weight:bold; color:#FFE100;";
					} else if (countryRecord.getGamesWon() < 0.8) {
						return "font-weight:bold; color:#7BFF00;";
					} else if (countryRecord.getGamesWon() <= 1) {
						return "font-weight:bold; color:#09FF00;";
					} else {
						return super.getCellCSSText(record, rowNum, colNum);
					}
				} else {
					return super.getCellCSSText(record, rowNum, colNum);
				}
			}
		};
		userListGrid.setAlign(Alignment.CENTER);
		userListGrid.setWidth(400);
		userListGrid.setHeight(400);
		userListGrid.setAlternateRecordStyles(true);
		// countryGrid.setShowAllRecords(true);

		ListGridField nameField = new ListGridField("név", "Név", 40);
		nameField.setAlign(Alignment.LEFT);
		ListGridField gamesPlayedField = new ListGridField("játékszám",
				"Játékok száma");
		gamesPlayedField.setType(ListGridFieldType.INTEGER);
		gamesPlayedField.setAlign(Alignment.CENTER);
		ListGridField gamesWonField = new ListGridField("arány",
				"Nyerési arány (%)");
		gamesWonField.setType(ListGridFieldType.INTEGER);
		gamesWonField.setAlign(Alignment.CENTER);
		gamesWonField.setCellFormatter(new CellFormatter() {

			@Override
			public String format(Object value, ListGridRecord record,
					int rowNum, int colNum) {
				if (value == null)
					return null;
				NumberFormat nf = NumberFormat.getFormat("##.#%");
				try {
					return nf.format(((Number) value).floatValue());
				} catch (Exception e) {
					return value.toString();
				}
			}
		});

		userListGrid.setFields(nameField, gamesPlayedField, gamesWonField); //
		// countryGrid.setCanResizeFields(true);
		verticalPanel.add(userListGrid);
		// countryGrid.addData(new UserListRecord("test", 1, 1));
		// countryGrid.addData(new UserListRecord("test2", 10, 12));
		userListGrid.setSelectionType(SelectionStyle.SINGLE);
		// countryGrid.redraw();
		userListGrid.addSelectionChangedHandler(new SelectionChangedHandler() {
			public void onSelectionChanged(SelectionEvent event) {
				String playerName = // ((UserListRecord)
				// event.getSelectedRecord())
				// .getUserName();
				event.getRecord().getAttributeAsString("név");
				selectedPlayerName.setText(playerName);
				if (playerName.equals(UI.currentUser.getUsername())) {
					gameStarterButton.setEnabled(false);
				} else {
					gameStarterButton.setEnabled(true);
				}
				selectedPlayerStats.setEnabled(true);
			}
		});
		gameStarterButton.addClickHandler(new ClickHandler() {

			@Override
			public void onClick(ClickEvent event) {
				User u = new User();
				u.setUsername(selectedPlayerName.getText());
				UserListWindow.proposeGameTo(u);
			}
		});
		selectedPlayerStats.addClickHandler(new ClickHandler() {

			@Override
			public void onClick(ClickEvent event) {
				UserStatsWindow usw = new UserStatsWindow(true);
				for (User u : loggedinUsers) {
					String username = ((UserListRecord) userListGrid.getSelectedRecord()).getUserName();
					if (username.equals(u.getUsername())) {
						usw.setUserStats(u);
					}
				}
				UI.mainMenuDecoratedTabPanel.add(usw, selectedPlayerName
						.getText()
						+ " statisztikái", false);
			}
		});

	}

	public void getUserListFromServer() {
		ServicesAsync services = (ServicesAsync) GWT.create(Services.class);
		ServiceDefTarget target = (ServiceDefTarget) services;
		String relativeUrl = GWT.getModuleBaseURL() + "Services";
		target.setServiceEntryPoint(relativeUrl);
		// services
		UI.servicesHandler
				.getLoggedInUsersList(new AsyncCallback<ArrayList<User>>() {

					@Override
					public void onFailure(Throwable caught) {
						System.err.println("NYÁ");

					}

					@Override
					public void onSuccess(ArrayList<User> result) {
						loggedinUsers.clear();
						loggedinUsers.addAll(result);
						refreshUserList();
					}
				});
		UI.servicesHandler
				.getLoggedInUsersStats(new AsyncCallback<ArrayList<UserStats>>() {

					@Override
					public void onSuccess(ArrayList<UserStats> result) {
						userStats.clear();
						userStats.addAll(result);
						refreshUserList();
					}

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

					}
				});
		// refreshUserList();
	}

	public void refreshUserList() {
		/*
		 * for (int i = 1; i < userListflexTable.getRowCount(); i++) {
		 * userListflexTable.removeRow(i); }
		 */

		/*
		 * for (int i = 1; i <= loggedinUsers.size(); i++) { final User u =
		 * loggedinUsers.get(i - 1); User temp = loggedinUsers.get(i - 1);
		 * UserStats uStats = new UserStats(); for (UserStats us : userStats) {
		 * if (us.getPlayerid() == u.getId()) { uStats = us; break; } }
		 * 
		 * final Button playWithPlayerButton = new Button(
		 * "Játék indítása ellene"); playWithPlayerButton.addClickHandler(new
		 * ClickHandler() {
		 * 
		 * @Override public void onClick(ClickEvent event) {
		 * UserListWindow.proposeGameTo(u);
		 * 
		 * }
		 * 
		 * });
		 * 
		 * Button getSelectedUserStats = new Button(u.getUsername());
		 * getSelectedUserStats.addClickHandler(new ClickHandler() {
		 * 
		 * @Override public void onClick(ClickEvent event) { final
		 * UserStatsWindow usw = new UserStatsWindow(true);
		 * UI.mainMenuDecoratedTabPanel.add(usw, u.getUsername() +
		 * " statisztikái", false);
		 * 
		 * boolean found = false; for (UserStats us : userStats) { if
		 * (us.getPlayerid() == u.getId()) { usw.setUserStats(us); found = true;
		 * break; } } if (found == false) UI.servicesHandler.getUserStats(u, new
		 * AsyncCallback<UserStats>() {
		 * 
		 * @Override public void onSuccess(UserStats result) {
		 * usw.setUserStats(result);
		 * 
		 * }
		 * 
		 * @Override public void onFailure(Throwable caught) { // TODO
		 * Auto-generated method stub
		 * 
		 * } }); } });
		 * 
		 * userListflexTable.setWidget(i, 0, getSelectedUserStats);
		 * userListflexTable.setWidget(i, 1, new Label(uStats.getGamesplayed() +
		 * " db")); Label l = new Label(uStats.getGamesplayed() == 0 ? 0 + " %"
		 * : (uStats.getGameswon() / (double) uStats.getGamesplayed()) 100 +
		 * "%");
		 * 
		 * userListflexTable.setWidget(i, 2, l); if (temp.getId() !=
		 * UI.currentUser.getId()) userListflexTable.setWidget(i, 3,
		 * playWithPlayerButton);
		 * 
		 * for (int j = 0; j <= 3; j++) {
		 * userListflexTable.getCellFormatter().setHorizontalAlignment(i, j,
		 * HasHorizontalAlignment.ALIGN_CENTER);
		 * userListflexTable.getCellFormatter().setVerticalAlignment(i, j,
		 * HasVerticalAlignment.ALIGN_MIDDLE); }
		 */
		userListGrid.selectAllRecords();
		userListGrid.removeSelectedData();
		for (User u : loggedinUsers) {
			for (UserStats us : userStats) {
				if (us.getPlayerid() == u.getId()) {
					double ratio = us.getGamesplayed() == 0 ? 0.0 : (double) us
							.getGameswon()
							/ (double) us.getGamesplayed();
					userListGrid.addData(new UserListRecord(u.getUsername(), us
							.getGamesplayed(), ratio));
				}
			}
		}
		userListGrid.redraw();
	}

	// }

	protected static void proposeGameTo(final User u) {
		ServicesAsync services = (ServicesAsync) GWT.create(Services.class);
		ServiceDefTarget target = (ServiceDefTarget) services;
		String relativeUrl = GWT.getModuleBaseURL() + "Services";

		services.proposeGameTo(UI.currentUser, u, new AsyncCallback<String>() {

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

			}

			@Override
			public void onSuccess(String result) {
				String answer;
				if (result.equals("true")) {
					answer = "Az ellenfél elfogadta a felkérést, játék indítása...";
					GameDialog gd = new GameDialog();
					gd.opponent = u;
					gd.center();
					gd.colorButtons();
					gd.isMineTurn = true;
					gd.setTitle("Ön lép!");
					UI.waitingDialog.hide();
				} else if (result.equals("false"))
					answer = "Az ellenfél elutasította a felkérést, próbáljon meg egy másik játékost!";
				else
					answer = "Az ellenfél nem válaszolt időben (30mp), próbálj meg egy másik játékost!";
				WaitingDialog.lblAnswer.setText(answer);
			}
		});

	}
}
