//	Contour - Android drawing teacher application
//	Copyright (C) 2014  Johannes Riedmann
//	
//	This program is free software: you can redistribute it and/or modify
//	it under the terms of the GNU General Public License as published by
//	the Free Software Foundation, either version 3 of the License, or
//	(at your option) any later version.
//	
//	This program is distributed in the hope that it will be useful,
//	but WITHOUT ANY WARRANTY; without even the implied warranty of
//	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//	GNU General Public License for more details.
//	
//	You should have received a copy of the GNU General Public License
//	along with this program.  If not, see <http://www.gnu.org/licenses/>.

package com.j0h1.contour.admin.client;

import java.util.ArrayList;

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.uibinder.client.UiBinder;
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.Widget;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.user.client.ui.FlexTable;
import com.google.gwt.user.client.ui.Label;
import com.j0h1.contour.admin.client.service.PlayerService;
import com.j0h1.contour.admin.client.service.PlayerServiceAsync;
import com.j0h1.contour.admin.shared.domain.Player;

/**
 * View that contains the UI elements and logic to delete an existing player.
 * @author Johannes Riedmann
 *
 */
public class DeletePlayerView extends Composite{

	private static DeletePlayerViewUiBinder uiBinder = GWT
			.create(DeletePlayerViewUiBinder.class);
	
	@UiField FlexTable ftbDeletePlayer;
	@UiField Label lblStatus;

	interface DeletePlayerViewUiBinder extends UiBinder<Widget, DeletePlayerView> {		
	}

	public DeletePlayerView() {
		initWidget(uiBinder.createAndBindUi(this));
		
		refreshData();
	}
	
	private void setFlexTableHeaderData() {
		ftbDeletePlayer.setText(0, 0, "PlayerId");
		ftbDeletePlayer.setText(0, 1, "Playername");
		ftbDeletePlayer.setText(0, 2, "PhoneId");
	}
	
	public void refreshData() {
		ftbDeletePlayer.removeAllRows();
		
		setFlexTableHeaderData();
		
		PlayerServiceAsync playerService = GWT.create(PlayerService.class);
		
		AsyncCallback<ArrayList<Player>> callback = new AsyncCallback<ArrayList<Player>>() {
			@Override
			public void onFailure(Throwable caught) {
				lblStatus.setText(caught.getMessage());
			}

			@Override
			public void onSuccess(ArrayList<Player> result) {
				if (result.size() == 0) {
					lblStatus.setText("No players found in database.");
				} else {
					populateFlexTable(result);
					lblStatus.setText("");
				}				
			}			
		};
		
		playerService.findAll(callback);
	}
	
	private void populateFlexTable(ArrayList<Player> players) {
		for (int i = 0; i < players.size(); i++) {
			Button removeButton = new Button("x");
			removeButton.addClickHandler(new ClickHandler() {
				@Override
				public void onClick(ClickEvent event) {
					final int rowIndex = ftbDeletePlayer.getCellForEvent(event).getRowIndex();
					
					// delete player
					String playerIdString = ftbDeletePlayer.getText(rowIndex, 0);
					int playerId = Integer.valueOf(playerIdString);
					
					final String playername = ftbDeletePlayer.getText(rowIndex, 1);
					
					// call service and delete
					PlayerServiceAsync playerService = GWT.create(PlayerService.class);
					
					AsyncCallback<Void> callback = new AsyncCallback<Void>() {
						@Override
						public void onFailure(Throwable caught) {
							setStatusLabel(caught.getMessage(), true);
						}

						@Override
						public void onSuccess(Void result) {
							ftbDeletePlayer.removeRow(rowIndex);
							setStatusLabel("Successfully deleted player \"" + playername + "\"", false);
						}
					};
					
					playerService.delete(playerId, callback);
				}				
			});
			
			ftbDeletePlayer.setText(i + 1, 0, String.valueOf(players.get(i).getPlayerId()));
			ftbDeletePlayer.setText(i + 1, 1, players.get(i).getPlayername());
			ftbDeletePlayer.setText(i + 1, 2, players.get(i).getPhoneId());
			ftbDeletePlayer.setWidget(i + 1, 3, removeButton);
		}
	}
	
	/**
	 * Set the status label to a given text for feedback.
	 * @param text		Exception/success message.
	 * @param isError 	Flag that defines if the current message is a
	 * 					error message.
	 */
	private void setStatusLabel(String text, boolean isError) {
		lblStatus.setVisible(true);
		lblStatus.setText(text);
		
		if (isError) {
			lblStatus.getElement().getStyle().setColor("red");
		} else {
			lblStatus.getElement().getStyle().setColor("green");
		}
		
		Timer t = new Timer() {
			public void run() {
				lblStatus.setVisible(false);
			}
		};

		t.schedule(3000);
	}

}
