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

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

import	jp.co.iti.swf.*;

/**
 * リンクを辿るためにページからリンクを抜き出すスレッド。
 */
public class WebSwfScanRobo extends Thread{
	private Vector				myScanQueue;
	private	Vector				myExtractQueue;
	private	WebRoboState		myState;
	private	WebMessages			myMessages;
	
	public	long				SleepTime	= 4000;	// 4sec
	
	/**
	 * コンストラクタ
	 * @since	1.00
	 */
	public WebSwfScanRobo(WebRoboState state ,Vector scanQueue ,Vector extractQueue ,WebMessages messages){
		myScanQueue		= scanQueue;
		myExtractQueue	= extractQueue;
		myMessages		= messages;
		
		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{
					// SWFドキュメントを開く
					SWFDocument swfdoc	= new SWFDocument((null==property.file) ?
													property.url.toExternalForm() :
													property.file.getAbsolutePath());
					
					// SWFドキュメントからURL取得
					String[] urls = swfdoc.getURLs();
					
					for(int i=urls.length-1;0<=i;i--){
						/* t3-nishimura@nri modification start */
						if (property.linkbase == null) {
							myExtractQueue.add(new DownloadProperty(property.url ,urls[i]));
						} else {
							myExtractQueue.add(new DownloadProperty(property.linkbase ,urls[i]));
						}
						/* t3-nishimura@nri modification end */
					}
					
				}
				catch(FileNotFoundException e){
					myMessages.add(myMessages.FileNotFoundSR,
						(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(Exception e){ e.printStackTrace(); }
			}
			catch(ArrayIndexOutOfBoundsException e){} // 先に他のスレッドに取られた。
			finally{ myState.alive--; }
		}
	}
}
