//	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.CheckBox;
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.ImageService;
import com.j0h1.contour.admin.client.service.ImageServiceAsync;
import com.j0h1.contour.admin.shared.domain.Image;

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

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

	interface DeleteImageViewUiBinder extends UiBinder<Widget, DeleteImageView> {
	}

	public DeleteImageView() {
		initWidget(uiBinder.createAndBindUi(this));
		
		refreshData();
	}
	
	private void setFlexTableHeaderData() {
		ftbDeleteImages.setText(0, 0, "ImageID");
		ftbDeleteImages.setText(0, 1, "Title (en)");
		ftbDeleteImages.setText(0, 2, "In Track?");
		ftbDeleteImages.setText(0, 3, "Delete?");
	}
	
	public void refreshData() {
		ftbDeleteImages.removeAllRows();
		
		setFlexTableHeaderData();
		
		// calling service to receive List of all non-deleted images and handling callback 
		ImageServiceAsync imageService = GWT.create(ImageService.class);

		AsyncCallback<ArrayList<Image>> callback = new AsyncCallback<ArrayList<Image>>() {
			public void onFailure(Throwable caught) {
				setStatusLabel(caught.getMessage(), true);
			}

			public void onSuccess(ArrayList<Image> result) {
				populateFlexTable(result);
			}
		};

		imageService.findAll(callback);
	}
	
	/**
	 * populates FlexTable with image metadata (id, name, image_in_track)
	 * @param images ArrayList with images received from server
	 */
	public void populateFlexTable(ArrayList<Image> images) {
		for (int i = 0; i < images.size(); i++) {
			// CheckBox to visualize if in Track or not
			CheckBox inTrackBox = new CheckBox();
			inTrackBox.setValue(images.get(i).isInTrack());
			inTrackBox.setEnabled(false);
			
			// Button to delete Image
			Button removeButton = new Button("x");
			removeButton.addClickHandler(new ClickHandler() {
				@Override
				public void onClick(ClickEvent event) {
					final int rowIndex = ftbDeleteImages.getCellForEvent(event).getRowIndex();
					
					// extracting imageId from FlexTable
					String imageIdString = ftbDeleteImages.getText(rowIndex, 0);
					int imageId = Integer.valueOf(imageIdString);
					
					// handling callback from ImageService
					ImageServiceAsync imageService = GWT.create(ImageService.class);
					
					AsyncCallback<Void> callback = new AsyncCallback<Void>() {
						public void onFailure(Throwable caught) {
							setStatusLabel(caught.getMessage(), true);
						}

						public void onSuccess(Void result) {
							// FlexTable is automatically reloaded after clicking on it,
							// so no need to remove the row
							setStatusLabel("Image successfully deleted.", false);
						}
					};
					
					// calling ImageService to delete image with specified id
					imageService.delete(imageId, callback);
				}				
			});
			
			// populate FlexTable with Text/ predefined Widgets
			ftbDeleteImages.setText(i + 1, 0, String.valueOf(images.get(i).getImageId()));
			ftbDeleteImages.setText(i + 1, 1, images.get(i).getTitleEN());
			ftbDeleteImages.setWidget(i + 1, 2, inTrackBox);
			ftbDeleteImages.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);
	}

}
