001package edu.pdx.cs410J.whitlock.client;
002
003import com.google.common.annotations.VisibleForTesting;
004import com.google.gwt.core.client.EntryPoint;
005import com.google.gwt.core.client.GWT;
006import com.google.gwt.event.dom.client.ClickEvent;
007import com.google.gwt.event.dom.client.ClickHandler;
008import com.google.gwt.user.client.Window;
009import com.google.gwt.user.client.rpc.AsyncCallback;
010import com.google.gwt.user.client.ui.*;
011
012import java.util.Collection;
013
014/**
015 * A basic GWT class that makes sure that we can send an appointment book back from the server
016 */
017public class AppointmentBookGwt implements EntryPoint {
018  private final Alerter alerter;
019
020  @VisibleForTesting
021  Button button;
022  TextBox textBox;
023
024  public AppointmentBookGwt() {
025    this(new Alerter() {
026      @Override
027      public void alert(String message) {
028        Window.alert(message);
029      }
030    });
031  }
032
033  @VisibleForTesting
034  AppointmentBookGwt(Alerter alerter) {
035    this.alerter = alerter;
036
037    addWidgets();
038  }
039
040  private void addWidgets() {
041    button = new Button("Ping Server");
042    button.addClickHandler(new ClickHandler() {
043      @Override
044      public void onClick(ClickEvent clickEvent) {
045        createAppointments();
046      }
047    });
048
049    this.textBox = new TextBox();
050  }
051
052  private void createAppointments() {
053    AppointmentBookServiceAsync async = GWT.create(AppointmentBookService.class);
054    int numberOfAppointments = getNumberOfAppointments();
055    async.createAppointmentBook(numberOfAppointments, new AsyncCallback<AppointmentBook>() {
056
057      @Override
058      public void onSuccess(AppointmentBook airline) {
059        displayInAlertDialog(airline);
060      }
061
062      @Override
063      public void onFailure(Throwable ex) {
064        alert(ex);
065      }
066    });
067  }
068
069  private int getNumberOfAppointments() {
070    String number = this.textBox.getText();
071
072    return Integer.parseInt(number);
073  }
074
075  private void displayInAlertDialog(AppointmentBook airline) {
076    StringBuilder sb = new StringBuilder(airline.toString());
077    sb.append("\n");
078
079    Collection<Appointment> flights = airline.getAppointments();
080    for (Appointment flight : flights) {
081      sb.append(flight);
082      sb.append("\n");
083    }
084    alerter.alert(sb.toString());
085  }
086
087  private void alert(Throwable ex) {
088    alerter.alert(ex.toString());
089  }
090
091  @Override
092  public void onModuleLoad() {
093    RootPanel rootPanel = RootPanel.get();
094    rootPanel.add(button);
095
096    DockPanel panel = new DockPanel();
097    panel.add(new Label("Number of appointments"), DockPanel.WEST);
098    panel.add(textBox, DockPanel.CENTER);
099
100    rootPanel.add(panel);
101  }
102
103  @VisibleForTesting
104  interface Alerter {
105    void alert(String message);
106  }
107
108}