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

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

import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.ISelectionChangedListener;
import org.eclipse.jface.viewers.SelectionChangedEvent;
import org.eclipse.jface.viewers.StructuredSelection;
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.layout.GridData;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.TableColumn;
import org.postgresforest.tool.action.DbInstanceAction;
import org.postgresforest.tool.bean.DbLinkInfo;
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.ViewControl;
import org.postgresforest.tool.view.action.AddDbAction;
import org.postgresforest.tool.view.action.AddDbInstanceAction;
import org.postgresforest.tool.view.action.DelDbAction;
import org.postgresforest.tool.view.action.DelDbInstanceAction;

/**
 * TODO To change the template for this generated type comment go to
 * Window - Preferences - Java - Code Style - Code Templates
 */
public class DbInstanceView extends ViewBase {

	public static final String ID = "org.postgresforest.tool.view.DbInstanceView";
	
	private TableTreeViewer m_viewer = null;

	/* (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);

		Table table = tree.getTable();
		table.setHeaderVisible(true);
		table.setLinesVisible(true);
        GridData gridData = new GridData();
        gridData.horizontalAlignment = GridData.FILL;
        gridData.verticalAlignment = GridData.FILL;
        gridData.grabExcessHorizontalSpace = true;
        gridData.grabExcessVerticalSpace = true;
        tree.setLayoutData(gridData);
		
		TableColumn column = new TableColumn(table, SWT.LEFT, 0);
		column.setText(Messages.getString("form.db.name"));
		column.setWidth(100);
		column = new TableColumn(table, SWT.LEFT, 1);
		column.setText(Messages.getString("form.db.hostname"));
		column.setWidth(100);
		column = new TableColumn(table, SWT.LEFT, 2);
		column.setText(Messages.getString("form.db.port"));
		column.setWidth(100);
		
		m_viewer = new TableTreeViewer(tree);
		
		m_viewer.setContentProvider(new TreeNodeContentProvider());

		
		m_viewer.setLabelProvider(new DbInstanceLabelProvider());
		m_viewer.addSelectionChangedListener(new TableListSelectionChangedListener());
		//MASUCOMMENT 右クリック対策
		createContextMenu(m_viewer.getTableTree());
	}

	
	
	
	/**
	 * 選択サーバID取得処理
	 * 
	 * @return サーバID
	 */
	public int getSelectInstanceId() {
		
	    Object node = getSelectNode();
	    if (node instanceof InstanceNode) {
            InstanceNode instanceNode = (InstanceNode) node;
            return instanceNode.getServerInfo().getId();
            
        }
		return -1;

	}
	
	/**
	 * データベース一覧の取得
	 *
	 */
	private ArrayList getDbLinkList() {
		ArrayList dbList = null;
		DbInstanceAction dbInstance = new DbInstanceAction(getGsc());
		try {
			dbList = dbInstance.getDbLinkList();
		} catch (Exception e) {
			e.printStackTrace();
			ErrorLog.log("", e);
		}
		
		return dbList;
	}
	
	public void update() {
		
	    if(!isLogin()){
			m_viewer.setInput(null);
			setEnabledActionAll(false);

			return;
	    }	    
	    //DBリンク情報を取得
		ArrayList dbLinkList = getDbLinkList();

		TreeNode treeRootItem = new TreeNode(null);

		for (Iterator iter = dbLinkList.iterator(); iter.hasNext();) {
			DbLinkInfo dbInfo = (DbLinkInfo) iter.next();

			TreeNode treeDbItem = new TreeNode(dbInfo.getName());
			treeRootItem.add(treeDbItem);
			
			ArrayList serrerList = dbInfo.getServer();
			for (Iterator itr2 = serrerList.iterator(); itr2.hasNext();) {
    			InstanceNode treeInstanceItem = new InstanceNode((ServerInfo)itr2.next());
    			treeDbItem.add(treeInstanceItem);
            }
			
		}

		
		//TableViewerにサーバ情報を設定
		m_viewer.setInput(treeRootItem);
		m_viewer.expandAll();

        setEnabledAction(AddDbAction.ID,EnableSelection.TRUE);


	}
	
	/**
	 * @return serrerList を戻します。
	 */
	public ArrayList getSerrerList() {
	    ArrayList serverList = new ArrayList();
	    List instanceNodes = null; 
	    
	    Object node = getSelectNode();
	    if (node instanceof InstanceNode) {
            InstanceNode instanceNode = (InstanceNode) node;
            instanceNodes = instanceNode.getParent().getChildren();
            
        }if (node instanceof TreeNode) {
            TreeNode treeNode = (TreeNode) node;
            instanceNodes = treeNode.getChildren();
            
        }
	    for (Iterator iter = instanceNodes.iterator(); iter.hasNext();) {
            InstanceNode element = (InstanceNode) iter.next();
            serverList.add(element.getServerInfo());
        }
	    
		return serverList;
	}
	
	/**
	 * 
	 * テーブル一覧のクリック時の処理。
	 * 
	 */
    class TableListSelectionChangedListener implements ISelectionChangedListener {

		/* (非 Javadoc)
		 * @see org.eclipse.jface.viewers.ISelectionChangedListener#selectionChanged(org.eclipse.jface.viewers.SelectionChangedEvent)
		 */
		public void selectionChanged(SelectionChangedEvent event) {

	        String dbName = null;
		    ISelection selection = event.getSelection();

	        //アクションボタン制御
		    Object selectObj =
                 ((StructuredSelection) selection)
                    .getFirstElement();
            if (selectObj instanceof InstanceNode) {

                setEnabledAction(DelDbInstanceAction.ID, EnableSelection.TRUE);
                setEnabledAction(AddDbInstanceAction.ID, EnableSelection.FALSE);
                setEnabledAction(DelDbAction.ID,EnableSelection.FALSE);

                InstanceNode instanceNode =(InstanceNode)selectObj; 
                dbName = ((TreeNode)instanceNode).getParent().getContent();
                
                //        		view.setDb(dbName);
            }else if(selectObj instanceof TreeNode ){
                
                setEnabledAction(DelDbInstanceAction.ID, EnableSelection.FALSE);
                setEnabledAction(AddDbInstanceAction.ID, EnableSelection.TRUE);
                setEnabledAction(DelDbAction.ID,EnableSelection.TRUE);

                dbName = ((TreeNode)selectObj).getContent();

                
            }else{
                setEnabledAction(DelDbInstanceAction.ID, EnableSelection.FALSE);
                setEnabledAction(AddDbInstanceAction.ID, EnableSelection.FALSE);
                setEnabledAction(DelDbAction.ID,EnableSelection.FALSE);
            }
            
            
            //関連VIEW更新
            ViewControl.updateUserDataView(DbInstanceView.ID,dbName);
        }
    }

    /**
	 * 選択データベース名取得処理
	 * 
	 * @return データベース名
	 */
	public String getSelectDb() {
		
	    Object node = getSelectNode();
	    if (node instanceof InstanceNode) {
            InstanceNode instanceNode = (InstanceNode) node;
            return instanceNode.getParent().getContent();
            
        }if (node instanceof TreeNode) {
            TreeNode treeNode = (TreeNode) node;
            return treeNode.getContent();
            
        }
		return "";
	}
	
	private  Object getSelectNode(){
	    
	
		TableTreeItem[] selectItem = m_viewer.getTableTree().getSelection();
		if(selectItem.length == 1){
		    return selectItem[0].getData();
		}
		return null;
	
	}
	
	/**
	 * 
	 * @param dbName
	 * @since
	 */
    public void select(String dbName) {

        TreeNode rootNode = (TreeNode)m_viewer.getInput();
        TreeNode selectNode = (TreeNode)getSelectNode();
        
        List dbNodes = rootNode.getChildren();
        for (Iterator iter = dbNodes.iterator(); iter.hasNext();) {
            TreeNode dnNode = (TreeNode) iter.next();
            if( dnNode.getContent().equals(dbName)){
                if(!dnNode.equals(selectNode) ){
               
	                if(!dnNode.getChildren().contains(selectNode)){
	                    m_viewer.setSelection(new StructuredSelection(dnNode));
	                }
                }
                break;
            }
            
        }
        
        
    }
	
}
