package hiro.yoshioka.sql.util;

import hiro.yoshioka.util.ColorNameEnum;
import hiro.yoshioka.util.ColorUtil;
import hiro.yoshioka.util.FontNameEnum;
import hiro.yoshioka.util.FontUtil;

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.swt.SWT;
import org.eclipse.swt.custom.StyleRange;
import org.eclipse.swt.custom.StyledText;
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;

public class SqlKeyHighlightDialog extends Dialog {
	String sql_statement;
	static Pattern P;
	static {
		P = Pattern
				.compile(
						"(CREATE|OR|TEXT|RETURNS|RETURN|INTEGER|BEGIN|END|END;|FUNCTION|REPLACE|TABLE|TABLESPACE|PRIMARY|KEY|VARCHAR2?|NUMBER|DATE|TIMESTAMP|TIME|INT|DOUBLE|FLOAT|TEXT|BLOB|CLOB|BIT|BOOLEAN|BINARY|CONSTRAINT|FOREIGN)( |\\(|,|\r|\n)|([0-9.,]+)",
						Pattern.CASE_INSENSITIVE);
	}

	public SqlKeyHighlightDialog(Shell shell, String sql_statement) {
		super(shell);
		this.sql_statement = sql_statement;
	}

	@Override
	protected Point getInitialSize() {
		int width = 300;
		if (getParentShell().getBounds().width >= 500) {
			width = 500;
		} else if (getParentShell().getBounds().width >= 700) {
			width = 700;
		}
		return new Point(width, 300);
	}

	@Override
	protected Control createDialogArea(Composite parent) {
		StyledText text = new StyledText(parent, SWT.MULTI | SWT.V_SCROLL
				| SWT.H_SCROLL);
		text.setFont(FontUtil.getFont(FontNameEnum.Terminal_14));
		text.setText(sql_statement);
		text.setLayoutData(new GridData(GridData.FILL_BOTH));
		Matcher m = P.matcher(sql_statement);
		while (m.find()) {
			StyleRange style1 = new StyleRange();
			if (m.group(1) == null) {
				style1.start = m.start(3);
				style1.length = m.group(3).length();
				style1.foreground = ColorUtil.getColor(ColorNameEnum.NULL);
			} else {
				style1.start = m.start(1);
				style1.length = m.group(1).length();
				style1.foreground = ColorUtil.getColor(ColorNameEnum.CHANGE);
			}

			text.setStyleRange(style1);
		}
		return text;
	}

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

	@Override
	protected void createButtonsForButtonBar(Composite parent) {
		createButton(parent, IDialogConstants.OK_ID,
				IDialogConstants.CLOSE_LABEL, true);
	}
}
