/*
 * 作成日: 2008/08/05
 * 著作権: Copyright (c) 2005 ZIGEN
 * ライセンス：Eclipse Public License - v 1.0
 * 原文：http://www.eclipse.org/legal/epl-v10.html
 */
package zigen.plugin.db.ext.s2jdbc.wizards;

import java.util.ArrayList;
import java.util.List;

import org.eclipse.core.runtime.IStatus;
import org.eclipse.jdt.internal.ui.dialogs.StatusInfo;
import org.eclipse.jdt.internal.ui.dialogs.StatusUtil;
import org.eclipse.jface.dialogs.Dialog;
import org.eclipse.jface.resource.ImageDescriptor;
import org.eclipse.jface.resource.ImageRegistry;
import org.eclipse.jface.text.source.CompositeRuler;
import org.eclipse.jface.text.source.LineNumberRulerColumn;
import org.eclipse.jface.viewers.CellEditor;
import org.eclipse.jface.viewers.CheckboxCellEditor;
import org.eclipse.jface.viewers.ComboBoxCellEditor;
import org.eclipse.jface.viewers.ICellModifier;
import org.eclipse.jface.viewers.IStructuredContentProvider;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.ITableLabelProvider;
import org.eclipse.jface.viewers.LabelProvider;
import org.eclipse.jface.viewers.TableViewer;
import org.eclipse.jface.viewers.TextCellEditor;
import org.eclipse.jface.viewers.Viewer;
import org.eclipse.jface.wizard.WizardPage;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.FocusAdapter;
import org.eclipse.swt.events.FocusEvent;
import org.eclipse.swt.events.KeyAdapter;
import org.eclipse.swt.events.KeyEvent;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.TableColumn;
import org.eclipse.ui.PlatformUI;

import zigen.plugin.db.DbPlugin;
import zigen.plugin.db.ui.views.internal.SQLDocument;
import zigen.plugin.db.ui.views.internal.SQLSourceViewer;

public class NewFormWizardPage2 extends WizardPage {
	
	public static final String CHECKED_IMAGE = "checkedcenter"; //$NON-NLS-1$
	
	public static final String UNCHECKED_IMAGE = "uncheckedcenter"; //$NON-NLS-1$
	
	public static final String PUBLIC = "public";
	
	public static final String PRIVATE = "private";
	
	public static final String DEFAULT = "default";
	
	public static final String PROTECTED = "protected";
	
	private static ImageRegistry imageRegistry = new ImageRegistry();
	
	static {
		// String iconPath = "icons/";
		String iconPath = ""; //$NON-NLS-1$
		imageRegistry.put(CHECKED_IMAGE, ImageDescriptor.createFromFile(TableViewLabelProvider2.class, iconPath + CHECKED_IMAGE + ".gif")); //$NON-NLS-1$
		imageRegistry.put(UNCHECKED_IMAGE, ImageDescriptor.createFromFile(TableViewLabelProvider2.class, iconPath + UNCHECKED_IMAGE + ".gif")); //$NON-NLS-1$
		
		imageRegistry.put(PUBLIC, ImageDescriptor.createFromFile(TableViewLabelProvider2.class, iconPath + PUBLIC + ".gif")); //$NON-NLS-1$
		imageRegistry.put(PRIVATE, ImageDescriptor.createFromFile(TableViewLabelProvider2.class, iconPath + PRIVATE + ".gif")); //$NON-NLS-1$
		imageRegistry.put(DEFAULT, ImageDescriptor.createFromFile(TableViewLabelProvider2.class, iconPath + DEFAULT + ".gif")); //$NON-NLS-1$
		imageRegistry.put(PROTECTED, ImageDescriptor.createFromFile(TableViewLabelProvider2.class, iconPath + PROTECTED + ".gif")); //$NON-NLS-1$
	}
	
	class TableViewLabelProvider2 extends LabelProvider implements ITableLabelProvider {
		
		
		public String getColumnText(Object obj, int index) {
			try {
				if (obj instanceof FormProperty) {
					FormProperty element = (FormProperty) obj;
					
					switch (index) {
						case 0:
							return "";
							
						case 1:
							return String.valueOf(element.no);
							
						case 2:
							return element.name;
							
						case 3:
							return element.type;
						case 4:
							return FormProperty.COMBO_ITEM[element.modified];
							
						case 5:
							// return new Boolean(element.isRequired).toString();
							return null;
							
						default:
							break;
					}
					
				}
				return null;
				

			} catch (Exception e) {
				DbPlugin.log(e);
			}
			
			return null;
			
		}
		
		
		public Image getColumnImage(Object element, int columnIndex) {
			// if (columnIndex == 0) {
			// return getImage(((FormProperty) element).modified);
			// } else if (columnIndex == 4) {
			// return getImage(((FormProperty) element).isRequired);
			// }
			// return null;
			return (columnIndex == 5) ? getImage(((FormProperty) element).isRequired) : null;
		}
		
		public Image getImage(Object obj) {
			return null;
		}
		
		private Image getImage(boolean isSelected) {
			String key = isSelected ? CHECKED_IMAGE : UNCHECKED_IMAGE;
			return imageRegistry.get(key);
		}
		
		// private Image getImage(int i) {
		// switch (i) {
		// case FormProperty.MODIFIED_PUBLIC:
		// return imageRegistry.get(PUBLIC);
		// case FormProperty.MODIFIED_PRIVATE:
		// return imageRegistry.get(PRIVATE);
		// case FormProperty.MODIFIED_DEFAULT:
		// return imageRegistry.get(DEFAULT);
		// case FormProperty.MODIFIED_PROTECTED:
		// return imageRegistry.get(PROTECTED);
		// default:
		// break;
		// }
		// return null;
		//
		// }
	}
	
	class TableViewContentProvider2 implements IStructuredContentProvider {
		
		List contents;
		
		public TableViewContentProvider2() {}
		
		public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {
			if (newInput instanceof List) {
				contents = (List) newInput;
			} else {
				contents = null;
			}
		}
		
		public Object[] getElements(Object newInput) {
			// Object[] out = new Object[contents.length - 1]; // カラム専用データを除く
			// System.arraycopy(contents, 1, out, 0, out.length);
			// return out;
			return contents.toArray();
		}
		
		public void dispose() {
			contents = null;
		}
		

	}
	
	class CellModifier2 implements ICellModifier {
		
		protected TableViewer viewer;
		
		protected Object oldValue = null;
		
		protected Object newValue = null;
		
		
		public CellModifier2(TableViewer viewer) {
			this.viewer = viewer;
		}
		
		public boolean canModify(Object element, String property) {
			int index = Integer.parseInt(property);
			// modify 2007/11/02 ZIGEN 行番号を選択した場合は抜ける
			if (index == 0)
				return false;
			
			return true;
		}
		
		public Object getValue(Object element, String property) {
			int index = Integer.parseInt(property);// 数値に変換
			return "test";
		}
		
		/**
		 * 見た目上は更新するが、DBはまだアップデートしない
		 */
		public void modify(Object element, String property, Object value) {
			int index = Integer.parseInt(property);
			if (value == null)
				value = ""; //$NON-NLS-1$
			newValue = value;
		}
		
	}
	
	protected IStructuredSelection selection;
	
	Table table;
	
	TableViewer viewer;
	
	public void createControl(Composite parent) {
		initializeDialogUnits(parent);
		Composite main = new Composite(parent, SWT.NONE);
		main.setFont(parent.getFont());
		int nColumns = 1;
		
		// createSQLInputPart(main);
		
		GridLayout layout = new GridLayout();
		layout.numColumns = nColumns;
		main.setLayout(layout);
		// データ表示エリア
		table = new Table(main, SWT.MULTI | SWT.FULL_SELECTION | SWT.BORDER | SWT.H_SCROLL | SWT.V_SCROLL);
		GridData gridData2 = new GridData(GridData.FILL_BOTH);
		table.setLayoutData(gridData2);
		table.setHeaderVisible(true);
		table.setLinesVisible(true);
		table.setFont(DbPlugin.getDefaultFont());
		viewer = new TableViewer(table);
		
		for (int i = 0; i < HEADER.length; i++) {
			String str = HEADER[i];
			TableColumn col = new TableColumn(table, SWT.LEFT);
			col.setText(str);
			col.pack();
		}
		
		String[] properties = new String[HEADER.length];
		viewer.setColumnProperties(properties);
		final TableKeyEventHandler2 handler = new TableKeyEventHandler2(viewer);
		TableKeyAdapter2 keyAdapter = new TableKeyAdapter2(handler);
		

		CellEditor[] cellEditors = new CellEditor[properties.length];
		CellEditor cellEditor = null;
		for (int i = 0; i < HEADER.length; i++) {
			if (i == 4) {
				cellEditor = new ComboBoxCellEditor(table, FormProperty.COMBO_ITEM, SWT.READ_ONLY);
				cellEditor.getControl().addKeyListener(keyAdapter);
				cellEditor.getControl().addTraverseListener(keyAdapter);
				
			} else if (i == 5) {
				cellEditor = new CheckboxCellEditor(table, i);
				// CheckboxCellEditorは、TABキーが拾えない
				
			} else {
				cellEditor = new TextCellEditor(table, SWT.SINGLE);
				cellEditor.getControl().addKeyListener(keyAdapter);
				cellEditor.getControl().addTraverseListener(keyAdapter);
			}
			
			cellEditors[i] = cellEditor;
			properties[i] = String.valueOf(i);
		}
		

		// セル・エディタの設定
		viewer.setCellEditors(cellEditors);
		
		// セル・モディファイヤの設定
		viewer.setCellModifier(new TableCellModifier2(viewer));
		
		viewer.setContentProvider(new TableViewContentProvider2());
		viewer.setLabelProvider(new TableViewLabelProvider2());
		

		elements = new ArrayList<FormProperty>();
		FormProperty property = new FormProperty();
		property.no = 1;
		property.modified = FormProperty.MODIFIED_PUBLIC;
		property.name = "hoge";
		property.type = "String";
		elements.add(property);
		//
		// FormProperty property2 = new FormProperty();
		// property2.no = 2;
		// // property2.modified = "public";
		// property2.modified = FormProperty.MODIFIED_DEFAULT;
		// property2.name = "userName";
		// property2.type = "String";
		// elements.add(property2);
		
		viewer.setInput(elements);
		

		table.addKeyListener(new KeyAdapter() {
			
			public void keyPressed(KeyEvent e) {
				if (e.keyCode == SWT.F2) {
					// レコード選択を解除し、先頭のカラムを編集状態にする
					int row = handler.getSelectedRow();
					handler.editTableElement(row, 2);
					
				}
			}
		});
		table.addFocusListener(new FocusAdapter() {
			
			public void focusGained(FocusEvent e) {
				if (table.getSelectionIndex() == -1) {
					table.select(0); // 未選択の場合は、強制的に1レコード目を選択
					table.notifyListeners(SWT.Selection, null); // 選択状態を通知
					
				}
				
			}
		});
		
		setControl(main);
		Dialog.applyDialogFont(main);
		PlatformUI.getWorkbench().getHelpSystem().setHelp(main, "org.eclipse.jdt.ui.new_class_wizard_page_context");
	}
	
	List<FormProperty> elements;
	
	private static String[] HEADER = {"", "No", "名前", "型", "修飾子", "必須"};
	
	protected void createSQLInputPart(Composite header) {
		Composite sqlComposite = new Composite(header, SWT.NONE);
		sqlComposite.setLayout(new FillLayout());
		
		CompositeRuler ruler = new CompositeRuler();
		LineNumberRulerColumn rulerCol = new LineNumberRulerColumn();
		// LineNumberRulerColumnUtil.changeColor(colorManager, rulerCol);
		ruler.addDecorator(0, rulerCol);
		SQLSourceViewer sqlViewer = new SQLSourceViewer(sqlComposite, ruler, null, false, SWT.MULTI | SWT.H_SCROLL | SWT.V_SCROLL | SWT.BORDER);
		// initializeViewerFont(sqlViewer);
		
		// 元の処理
		sqlViewer.setDocument(new SQLDocument());
		

	}
	
	
	private IStatus fCurrStatus;
	
	private boolean fPageVisible;
	
	public NewFormWizardPage2(IStructuredSelection selection) {
		super("");
		super.setDescription("プロパティを追加してください");
		this.selection = selection;
		fPageVisible = false;
		fCurrStatus = new StatusInfo();
	}
	
	public void setVisible(boolean visible) {
		super.setVisible(visible);
		fPageVisible = visible;
		if (visible && fCurrStatus.matches(4)) {
			StatusInfo status = new StatusInfo();
			status.setError("");
			fCurrStatus = status;
		}
		updateStatus(fCurrStatus);
		

		if (visible) {
			setFocus();
		}
		
	}
	
	protected void updateStatus(IStatus status) {
		fCurrStatus = status;
		setPageComplete(!status.matches(4));
		if (fPageVisible)
			StatusUtil.applyToStatusLine(this, status);
	}
	
	protected void updateStatus(IStatus status[]) {
		updateStatus(StatusUtil.getMostSevere(status));
	}
	
	
	protected void setFocus() {
		
		TableColumn[] cols = table.getColumns();
		
		int size = HEADER.length;
		
		int w = (table.getBounds().width - 50) / (size - 1); // 先頭のNoカラム以外で計算
		
		cols[0].setWidth(0);
		cols[1].setWidth(40);
		for (int i = 2; i < size; i++) {
			TableColumn tableColumn = cols[i];
			tableColumn.setWidth(w);
		}
		

	}
	

}
