package net.kldp.logviewer;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import net.kldp.logviewer.common.log.LogViews;
import net.kldp.logviewer.db.LogViewerDB;
import net.kldp.logviewer.model.ILogListener;
import net.kldp.logviewer.model.LogViewer;
import net.kldp.logviewer.model.LogViewerEntry;
import net.kldp.logviewer.model.LogViewerGroup;

import org.apache.log4j.Logger;
import org.eclipse.core.runtime.IAdapterFactory;
import org.eclipse.core.runtime.Platform;
import org.eclipse.jface.viewers.TreeViewer;
import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.ui.model.BaseWorkbenchContentProvider;
import org.eclipse.ui.model.WorkbenchLabelProvider;
import org.eclipse.ui.part.ViewPart;


public class NavigationView extends ViewPart {
	private static final Logger logger = LogViews.getLogger(NavigationView.class);
	
	public static final String ID = "net.kldp.logviewer.navigationView";
	private TreeViewer treeViewer;
	
	LogViewerGroup root = null;	
	private IAdapterFactory adapterFactory = new LogAdapterFactory();
	
	public NavigationView() {
		super();
	}
	
	/**
	 * Passing the focus request to the viewer's control.
	 */
	public void setFocus() {
		treeViewer.getControl().setFocus();
	}
	
	public void dispose() {
		Platform.getAdapterManager().unregisterAdapters(adapterFactory);
		super.dispose();
	}

	/**
	 * 처음 시작할대 스트트 해야할 로그를 정의하고 표시한다.
	 *
	 */
	private void initializeSession() {
		logger.debug("[NavigationView Started...............]");
		
		root = new LogViewerGroup(null, 0, "RootGroup");
		
		String selGroup = "SELECT * FROM log_group WHERE status_yn = '00'";
		Connection conn = null;
		PreparedStatement stmtGrp = null;
	    ResultSet rsetGrp = null;
	
	    try {
	        conn = LogViewerDB.getInstance().getConnection();
	        stmtGrp = conn.prepareStatement(selGroup);
	        rsetGrp = stmtGrp.executeQuery();
	        
	        while(rsetGrp.next()) {
	        	long groupSeq = rsetGrp.getBigDecimal("SEQ").longValue();
	        	String groupName = rsetGrp.getString("GROUP_NAME");
	        		        	
	        	LogViewerGroup friendsGroup = new LogViewerGroup(root, groupSeq, groupName);
	        	root.addEntry(friendsGroup);
	        	
	        	// 나무잎을 추가한다.
	        	makeLeaf(friendsGroup, groupSeq);
	        }
	        
	    } catch(SQLException e) {
	        e.printStackTrace();
	    } finally {
	        try { rsetGrp.close(); } catch(Exception e) { }
	        try { stmtGrp.close(); } catch(Exception e) { }
	        try { conn.close(); } catch(Exception e) { }
	    }
	}
	
	/**
	 * Group의 나무잎을 추가한다.
	 * 
	 * @param group
	 * @param groupName
	 */
	private void makeLeaf(LogViewerGroup group, long _groupSeq) {
		String selGroup = "SELECT * FROM log_detail WHERE group_seq = ? AND status_yn = '00'";
		Connection conn = null;
		PreparedStatement stmtGrp = null;
	    ResultSet rsetGrp = null;
	
	    try {
	        conn = LogViewerDB.getInstance().getConnection();
	        stmtGrp = conn.prepareStatement(selGroup);
	        stmtGrp.setLong(1, _groupSeq);	        
	        rsetGrp = stmtGrp.executeQuery();	        
	        
	        while(rsetGrp.next()) {
	        	long groupSeq 	= rsetGrp.getBigDecimal("GROUP_SEQ").longValue();
	        	long seq 		= rsetGrp.getBigDecimal("SEQ").longValue();
	        	String name 	= rsetGrp.getString("NAME");
	        	String type 	= rsetGrp.getString("type");
	        	String ftpIP 	= rsetGrp.getString("ftpIP");
	        	String ftpPort 	= rsetGrp.getString("ftpPort");
	        	String ftpID 	= rsetGrp.getString("ftpID");
	        	String ftpPass 	= rsetGrp.getString("ftpPass");
	        	String ftpMode 	= rsetGrp.getString("ftpMode");	        
	        	
	        	String path 	= rsetGrp.getString("PATH");
	        	long delaySecond = rsetGrp.getBigDecimal("DELAY_SECOND").longValue();
	        	
	        	String font 		= rsetGrp.getString("FONT");
	        	String fontSize 	= rsetGrp.getString("font_size");
	        	String fontColor 	= rsetGrp.getString("font_color");
	        	String backgroundColor 	= rsetGrp.getString("background_color");
	
	        	String curBackColor 	= rsetGrp.getString("cur_back_color");
	          	String lineCount  		= rsetGrp.getString("line_count");
	          	String alalrmData		= rsetGrp.getString("alalrm_data");
	          	String alalrmBackColor  = rsetGrp.getString("alalrm_back_color");
	          	String alarmType 		= rsetGrp.getString("alarm_type");
	  
	        	group.addEntry(
	        			new LogViewerEntry(group, groupSeq, seq, name, type, ftpIP, ftpPort, ftpID, 
	        					ftpPass, ftpMode, path, delaySecond, font, fontSize, 
	        					fontColor, backgroundColor,
	        					curBackColor, lineCount, alalrmData, alalrmBackColor, alarmType
	        			));
	        }
	        
	    } catch(SQLException e) {
	        e.printStackTrace();
	    } finally {
	        try { rsetGrp.close(); } catch(Exception e) { }
	        try { stmtGrp.close(); } catch(Exception e) { }
	        try { conn.close(); } catch(Exception e) { }
	    }
	}
	
	public void createPartControl(Composite parent) {
		initializeSession(); 
		
		treeViewer = new TreeViewer(parent, SWT.BORDER | SWT.MULTI | SWT.V_SCROLL);
		getSite().setSelectionProvider(treeViewer);		
		Platform.getAdapterManager().registerAdapters(adapterFactory, LogViewer.class);
		
		treeViewer.setLabelProvider(new WorkbenchLabelProvider());
		treeViewer.setContentProvider(new BaseWorkbenchContentProvider());
		
		treeViewer.setInput(root);
		
		root.addContactsListener(new ILogListener() {
			public void logChanged(LogViewerGroup contacts, LogViewerEntry entry) {
				treeViewer.refresh();
			}
		});
		
	}
}
