/*
 * Copyright (C) 2005 NTT DATA Corporation
 * 
 */
package org.postgresforest.tool.view.serverstatus;

import java.util.ArrayList;
import java.util.Iterator;

import org.eclipse.jface.viewers.CellEditor;
import org.eclipse.jface.viewers.ComboBoxCellEditor;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.ISelectionChangedListener;
import org.eclipse.jface.viewers.SelectionChangedEvent;
import org.eclipse.jface.viewers.TableTreeViewer;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.TableTree;
import org.eclipse.swt.custom.TableTreeItem;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.TableColumn;
import org.postgresforest.tool.action.GscAction;
import org.postgresforest.tool.action.ServerAction;
import org.postgresforest.tool.bean.GSCInfo;
import org.postgresforest.tool.bean.InstanceNode;
import org.postgresforest.tool.bean.ServerInfo;
import org.postgresforest.tool.bean.TreeNode;
import org.postgresforest.tool.util.EnableSelection;
import org.postgresforest.tool.util.ErrorLog;
import org.postgresforest.tool.util.Messages;
import org.postgresforest.tool.util.TreeNodeContentProvider;
import org.postgresforest.tool.view.ViewBase;
import org.postgresforest.tool.view.action.AddGscAction;
import org.postgresforest.tool.view.action.AddInstanceAction;
import org.postgresforest.tool.view.action.DelGscAction;
import org.postgresforest.tool.view.action.DelInstanceAction;
import org.postgresforest.tool.view.action.ResetServerStatusAction;
import org.postgresforest.tool.view.action.SetServerStatusAction;


/**
 * サーバステータスビュークラス
 * 
 * サーバステータスを表示し、状態の変更を行う。
 */
public class ServerStatusView extends ViewBase {

	public static final String ID = "org.postgresforest.tool.view.ServerStatusView";
	
//	private TableViewer viewer = null;
	private TableTreeViewer viewer= null;

	protected ArrayList m_serverList;

	protected ArrayList m_gscList;


	/* (non-Javadoc)
	 * @see org.eclipse.ui.IWorkbenchPart#createPartControl(org.eclipse.swt.widgets.Composite)
	 */
	public void createPartControl(Composite parent) {
		TableTree tree = new TableTree(parent,
				SWT.H_SCROLL | SWT.V_SCROLL | SWT.FULL_SELECTION | SWT.SINGLE | SWT.MULTI|SWT.BORDER);
	//TODOMASU TableTreeに変更	
	//	Table table = new Table(parent,
	//			SWT.H_SCROLL | SWT.V_SCROLL | SWT.FULL_SELECTION | SWT.MULTI|SWT.BORDER);
		Table table = tree.getTable();
		table.setHeaderVisible(true);
		table.setLinesVisible(true);
		
		TableColumn column = new TableColumn(table, SWT.LEFT, 0);
		column.setText(Messages.getString("form.db.hostname") + "/" + Messages.getString("form.db.name"));
		column.setWidth(100);
		column = new TableColumn(table, SWT.LEFT, 1);
		column.setText(Messages.getString("form.db.port"));
		column.setWidth(50);
		column = new TableColumn(table, SWT.LEFT, 2);
		column.setText(Messages.getString("form.db.status"));
		column.setWidth(80);
		column = new TableColumn(table, SWT.LEFT, 3);
		column.setText(Messages.getString("form.db.update"));
		column.setWidth(80);
		column = new TableColumn(table, SWT.LEFT, 4);
		column.setText("");
		column.setWidth(0);
		column.setResizable(false);

		//TODOMASU TableTreeViewerを取得に変更
//		viewer = new TableViewer(table);
//		viewer.setContentProvider(new CommonTableContentProvider());
		viewer = new TableTreeViewer(tree);
		viewer.setContentProvider(new TreeNodeContentProvider());
		

		viewer.setLabelProvider(new ServerStatusLabelProvider());
		
		String[] properties = new String[]{
				"host",
				"port",
				"status",
				"change"
		};
		// カラム・プロパティの設定
		viewer.setColumnProperties(properties);

		
		String[] comboItem = new String[2];
		comboItem[0] = Messages.getString("form.running");
		comboItem[1] = Messages.getString("form.stopping");
		
	    // 各カラムに設定するセル・エディタの配列
		CellEditor[] editors = new CellEditor[]{ // ②
				null,
				null,
				null,
				new ComboBoxCellEditor(table, comboItem, SWT.READ_ONLY)
		};

	    //セル・エディタの設定
	    viewer.setCellEditors(editors);
	    
	    //セル・モディファイヤの設定
	    //TODOMASU TableViewではなくなるので、どうするか再検討
	    viewer.setCellModifier(new ServerStatusCellModifier(viewer));

	    //
	    viewer.addSelectionChangedListener(new ISelectionChangedListener(){
		    public void selectionChanged(SelectionChangedEvent event){
		    
 
		    	String id = getSelectId();
		    	//TODO MASU サーバIDが取得できなかった時は、削除を !!ログオフ時動きがおかしい
		    	if(id.equals("")){
		    		setEnabledAction(DelInstanceAction.ID, EnableSelection.FALSE);
		    		setEnabledAction(AddGscAction.ID,EnableSelection.FALSE);
		    		setEnabledAction(DelGscAction.ID,EnableSelection.TRUE);
		    		
		    	}else{
		    		ISelection selection = event.getSelection();
			        setEnabledAction(DelInstanceAction.ID,selection);
			        setEnabledAction(AddGscAction.ID,selection);
			        setEnabledAction(DelGscAction.ID,EnableSelection.FALSE);
		    	}
		    }
    								
		});		
	    //MASUCOMMENT 右クリック対策
		//createContextMenu(viewer.getTable());
	    createContextMenu(viewer.getTableTree());
	    
	}

	
	/**
	 * 
	 */
	public ArrayList getChgServerList() {
		//TableViewerからサーバ情報を取得
		return m_serverList;

	}
	
	/**
	 * 選択サーバID取得処理
	 * 
	 * @return サーバID
	 */
	public String getSelectId() {
		//TODOMASU GSCを選ばれた時は、IDは取れないことにする
		//Table tbl = viewer.getTable();
		//TableItem[] selectItem = tbl.getSelection();
		TableTree tblTree = viewer.getTableTree();
		TableTreeItem [] selectItem = tblTree.getSelection();
		//TODOMASU 本当にこれでServerIDが取得できるのか？要確認！
		if(selectItem.length == 1){
			return selectItem[0].getText(4);
		}
		else{
			return "";
		}
	}
	
	public TableTree getTableTree(){
		TableTree tblTree = viewer.getTableTree();
		return tblTree;
		
	}
	
	/**
	 * サーバ情報取得
	 * 
	 * @return サーバ情報
	 */
	private ArrayList getServerList() {
		ArrayList serverList = null;

		//サーバ情報取得
		ServerAction serverInfo = new ServerAction(getGsc());
		try {
			serverList = serverInfo.getServerList();
		} catch (Exception e) {
			ErrorLog.log("", e);
		}

		return serverList;
	}
	
	public void update() {
		if(!isLogin()){
			viewer.setInput(null);
			setEnabledAction(SetServerStatusAction.ID,EnableSelection.FALSE);
			setEnabledAction(ResetServerStatusAction.ID,EnableSelection.FALSE);
			setEnabledAction(AddInstanceAction.ID, EnableSelection.FALSE);
	        return;
	    }

	    m_serverList = getServerList();
		//GSC情報取得
		GscAction gsc = new GscAction(getGsc());
		try {
			m_gscList = gsc.getGscList();
		} catch (Exception e) {
			//TODO エラー処理
			e.printStackTrace();
			ErrorLog.log("", e);
		}

		TreeNode treeRootItem = new TreeNode(null);
		
		for(Iterator ite = m_serverList.iterator(); ite.hasNext();){
			ServerInfo serverInfo = (ServerInfo)ite.next();
			InstanceNode instanceNode = new InstanceNode(serverInfo);
			treeRootItem.add(instanceNode);
			
			//GSC DBがあるインスタンスの場合
			for (Iterator itr2 = m_gscList.iterator(); itr2.hasNext();) {
				GSCInfo gscInfo = (GSCInfo)itr2.next();
				if(gscInfo.getId() == serverInfo.getId()){
					TreeNode treeItem = new TreeNode(gscInfo.getDb());
	    			instanceNode.add(treeItem);
				}
            }
		}
		
		
		setEnabledAction(SetServerStatusAction.ID,EnableSelection.TRUE);
		setEnabledAction(ResetServerStatusAction.ID,EnableSelection.TRUE);
		setEnabledAction(AddInstanceAction.ID, EnableSelection.TRUE);
		//TableViewerにサーバ情報を設定
		//viewer.setInput(serverList);
		viewer.setInput(treeRootItem);
		viewer.expandAll();
		//setEnabledActionAll(true);

	}
	/**
	 * 最後のGSCかの判定処理
	 * 
	 * @return サーバID
	 */
	public boolean isLastGsc() {
		
		if(m_gscList.size() == 1){
			return true;
		}
		else{
			return false;
		}
	}
	
	
}
