/**
 * @(#)WebScanRobo.java
 * Copyright 2001 Nomura Research Institute, LTD. All rights reserved.
 * RIDUAL : Web Scan Robo
 * @author  Intelligent Technology Inc.
 * @version 1.00 2002/09/02
 */
package jp.co.nri.rid.web;

import	java.net.URL;
import	java.io.*;
import	java.util.Vector;
import	javax.swing.text.BadLocationException;

/**
 * リンクを辿るためにページからリンクを抜き出すスレッド。
 */
public class WebScanRobo extends Thread{
	private Vector				myScanQueue;
	private	Vector				myExtractQueue;
	private	WebPage				myWebPage;
	private	WebRoboState		myState;
	private	WebMessages			myMessages;
	
	public	long				SleepTime	= 4000;	// 4sec
	
	/**
	 * コンストラクタ
	 * @since	1.00
	 */
	public WebScanRobo(WebRoboState state ,Vector scanQueue ,Vector extractQueue ,WebMessages messages){
		myScanQueue		= scanQueue;
		myExtractQueue	= extractQueue;
		myMessages		= messages;
		
		myWebPage		= new WebPage();
		myWebPage.setKeytable(new WebKeyMap());
		
		myState = state;
	}
	
	/**
	 * ScanPropertyのurl、fileともnullの場合はNullPointerExceptionをスローする。
	 * @since	1.00
	 */
	public void run(){
		while(!myState.stopping){
			if(0 >= myScanQueue.size()){
				try{ sleep(SleepTime); }catch(InterruptedException e){}
				continue;
			}
			
			myState.alive++;
			
			try{
				Object obj = myScanQueue.remove(0);
				File file;
				if(!(obj instanceof ScanProperty))	continue;
				
				ScanProperty property = (ScanProperty)obj;
				try{
					if(null==property.file)	myWebPage.setPage(property.url);
					else					myWebPage.setPage(property.file);
					
					HashVector hv = myWebPage.get();
					addQueue(hv ,WebKeyMap.HYPERLINK,property.url);
					addQueue(hv ,WebKeyMap.CONTENTS	,property.url);
				}
				catch(FileNotFoundException e){ myMessages.add(myMessages.FileNotFoundSR ,(null==property.file) ? property.url.toString() : property.file.toString()); }
				catch(UnsupportedEncodingException e){ myMessages.add(myMessages.UnsupportedEncodingSR ,(null==property.file) ? property.url.toString() : property.file.toString()); }
				catch(IOException e){ myMessages.add(myMessages.IOErrorSR ,(null==property.file) ? property.url.toString() : property.file.toString()); } // ファイル関係で異常が発生した。
				catch(BadLocationException e){ myMessages.add(myMessages.IOErrorSR ,(null==property.file) ? property.url.toString() : property.file.toString()); }
			}
			catch(ArrayIndexOutOfBoundsException e){} // 先に他のスレッドに取られた。
			finally{ myState.alive--; }
		}
	}
	
	private void addQueue(HashVector hv ,String key ,URL parent){
		Vector vec = hv.get(key);
		if(null==vec)	return;
		
		String[] values	= (String[])vec.toArray(new String[0]);
		
		for(int i=values.length-1;0<=i;i--){
			myExtractQueue.add(new DownloadProperty(parent ,values[i]));
		}
	}
}
