package hiro.yoshioka.sql.twitter;

import hiro.yoshioka.util.StringUtil;

import org.eclipse.jface.dialogs.Dialog;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.swt.widgets.Shell;

import twitter4j.Twitter;
import twitter4j.TwitterException;
import twitter4j.TwitterFactory;
import twitter4j.auth.AccessToken;
import twitter4j.auth.RequestToken;
import twitter4j.conf.ConfigurationBuilder;

public class TwitterUtil {
	static final String CONSUMERKEY = Messages
			.getString("TwitterSQL.ConsumerKey");
	static final String CONSMERSECRET = Messages
			.getString("TwitterSQL.ConsumerSecret");

	public static WolfAccessToken getAccessTokenAtAuthorizationSite(
			final Shell shell) throws TwitterException {
		AccessToken accessToken = null;
		ConfigurationBuilder confbuilder = new ConfigurationBuilder();
		confbuilder.setOAuthConsumerKey(CONSUMERKEY);
		confbuilder.setOAuthConsumerSecret(CONSMERSECRET);

		TwitterFactory factory = new TwitterFactory(confbuilder.build());
		Twitter twitter = factory.getInstance();
		final RequestToken requestToken = twitter.getOAuthRequestToken();

		int retryCounter = 0;
		for (; null == accessToken && retryCounter < 5; retryCounter++) {
			System.out
					.println("Open the following URL and grant access to your account:");
			System.out.println(requestToken.getAuthorizationURL());
			final AuthorizeDialog dialog = new AuthorizeDialog(shell, twitter,
					requestToken);
			dialog.setBlockOnOpen(true);
			try {
				shell.getDisplay().syncExec(new Runnable() {
					@Override
					public void run() {
						dialog.open();
					}
				});
			} catch (Exception e) {
				e.printStackTrace();
			}

			accessToken = dialog.getAccessToken();
			if (accessToken == null && dialog.getReturnCode() == Dialog.CANCEL) {
				break;
			}
		}
		if (accessToken == null && retryCounter >= 5) {
			MessageDialog.openError(shell, StringUtil.EMPTY_STRING,
					"retry over...");
		}
		return new WolfAccessToken(accessToken);
	}
}
