package hiro.yoshioka.sql.twitter;

import hiro.yoshioka.util.StringUtil;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.eclipse.jface.dialogs.Dialog;
import org.eclipse.jface.dialogs.IDialogConstants;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.swt.SWT;
import org.eclipse.swt.browser.Browser;
import org.eclipse.swt.browser.LocationAdapter;
import org.eclipse.swt.browser.LocationEvent;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Shell;

import twitter4j.Twitter;
import twitter4j.TwitterException;
import twitter4j.auth.AccessToken;
import twitter4j.auth.RequestToken;

public class AuthorizeDialog extends Dialog {
	Browser browser;
	String url;
	Twitter twitter;
	RequestToken requestToken;
	AccessToken accessToken;
	Pattern OAUTH_VERIFIER_PATTERN = Pattern.compile("oauth_verifier=([0-9a-zA-Z]+)");

	protected AuthorizeDialog(Shell parentShell, Twitter twitter, RequestToken requestToken) {
		super(parentShell);
		this.twitter = twitter;
		this.requestToken = requestToken;
		this.url = requestToken.getAuthorizationURL();
	}
	@Override
	protected void buttonPressed(int buttonId) {
		if (IDialogConstants.CLOSE_ID == buttonId) {
			setReturnCode(CANCEL);
			close();
		} else {
			super.buttonPressed(buttonId);
		}
	}
	@Override
	protected void createButtonsForButtonBar(Composite parent) {
		createButton(parent, IDialogConstants.CLOSE_ID, IDialogConstants.CLOSE_LABEL, false);
	}

	@Override
	protected boolean isResizable() {
		return true;
	}

	@Override
	protected Control createDialogArea(Composite parent) {
		getShell().setText("Request For Permission");
		Composite c = (Composite) super.createDialogArea(parent);
		browser = new Browser(c, SWT.NONE);
		browser.setUrl(url);
		browser.addLocationListener(new LocationAdapter() {
			@Override
			public void changed(LocationEvent arg0) {
				Matcher m = OAUTH_VERIFIER_PATTERN.matcher(arg0.location);
				if (m.find()) {
					try {
						accessToken = twitter.getOAuthAccessToken(requestToken, m.group(1));
						MessageDialog.openInformation(getShell(), StringUtil.EMPTY_STRING, "authorization Success, push close button on this dialog.");
					} catch (TwitterException e) {
						e.printStackTrace();
					}
				}

			}
		});
		browser.setLayoutData(new GridData(GridData.FILL_BOTH));
		return c;
	}

	public AccessToken getAccessToken() {
		return accessToken;
	}

	protected Point getInitialSize() {
		return new Point(680, 680);
	}

	public void setUrl(String url) {
		browser.setUrl(url);
	}
}
