package com.piki.client.rpc;
import java.util.List;
import com.google.gwt.core.client.GWT;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.piki.client.storage.WikiStorage;
import com.piki.shared.model.WikiPage;
public class WikiPageDAOAsynImpl implements WikiPageDAOAsyn {
/**
* html5 storage
*/
private WikiStorage storage = null;
/**
* format service
*/
private FormatServiceAsync formatService = null;
/**
* default constructor
*/
public WikiPageDAOAsynImpl() {
this(new WikiStorage(), (FormatServiceAsync) GWT
.create(FormatService.class));
}
public WikiPageDAOAsynImpl(FormatServiceAsync formatService) {
this(new WikiStorage(), formatService);
}
/**
* format service
*
* @param storage
*/
public WikiPageDAOAsynImpl(WikiStorage storage) {
this(storage, (FormatServiceAsync) GWT.create(FormatService.class));
}
public WikiPageDAOAsynImpl(WikiStorage wikiStorage,
FormatServiceAsync formatService) {
this.storage = wikiStorage;
this.formatService = formatService;
}
@Override
public void read(String name, AsyncCallback<WikiPage> wikiPage) {
WikiPage result = new WikiPage();
result.setName(name);
result.setWiki(storage.read(name));
result.setHtml(storage.readHtml(name));
if (result.getWiki() == null)
wikiPage.onFailure(new Exception("html5 storage is not supported"));
else
wikiPage.onSuccess(result);
}
@Override
public void update(final WikiPage wiki,
final AsyncCallback<WikiPage> wikiResult) {
if (!storage.save(wiki.getName(), wiki.getWiki()))
wikiResult
.onFailure(new Exception("html5 storage is not supported"));
else {
formatService.format(GWT.getHostPageBaseURL(), wiki.getWiki(),
new AsyncCallback<String>() {
@Override
public void onFailure(Throwable caught) {
wikiResult.onFailure(caught);
}
@Override
public void onSuccess(String result) {
wiki.setHtml(result);
storage.saveHtml(wiki.getName(), result);
wikiResult.onSuccess(wiki);
}
});
}
}
@Override
public void delete(String name, AsyncCallback<Boolean> deleted) {
try {
deleted.onSuccess(storage.delete(name));
} catch (Exception exception) {
deleted.onFailure(exception);
}
}
@Override
public void readAll(AsyncCallback<List<String>> wikiPages) {
try {
wikiPages.onSuccess(storage.findAll());
} catch (Exception exception) {
wikiPages.onFailure(exception);
}
}
}