/* $Id: ZidestoreSpider.java,v 1.1 2004/01/09 16:54:18 burkhard Exp $
 * Created on 22.05.2003 by sell
 *
 */
package de.skyrix.zsp.logic;

import java.net.URL;

import de.skyrix.zsp.conf.ZSPConfig;
import de.skyrix.zsp.event.CacheEvent;
import de.skyrix.zsp.event.CacheListener;
import de.skyrix.zsp.event.ConfigChangeEvent;
import de.skyrix.zsp.event.ConfigChangeListener;
import de.skyrix.zsp.logic.cache.CacheManager;

/**
 * 
 * @author sell
 * @version 
 */
public class ZidestoreSpider {
	private ZidestoreConnection connection;
	private static boolean spiderRunning = false;
	private static ZidestoreSpider selfInstance = null;
	private boolean abortCurrentAction = false;
	private boolean stopSpider = false;

	private ZidestoreSpider() {
	};

	public ZidestoreSpider(String userName, String password, String url) {
		connection = new ZidestoreConnection();

		connection.addCacheListener(new CacheListener() {
			public void collectionFound(CacheEvent e) {
				checkFolder(e.getDavItem());
			}
		});

		//Register ConfigChangeListener
		ZSPConfig.addConfigChangeListener(new ConfigChangeListener() {

			public void configurationChanged(ConfigChangeEvent e) {
				abortCurrentSpiderAction();
				checkConfig();
			}
		});

		selfInstance = this;
		checkConfig();
	}

	private void checkConfig() {
		//TODO: check config an start/stop spider, set interval,...
		if ("true".equals(ZSPConfig.getProperty("enable_spider"))) {
			stopSpider = false;
			startSpider(true);
		}
		else {
			stopSpider = true;
		}
	}

	public void abortCurrentSpiderAction() {
		if (!spiderRunning)
			return;

		abortCurrentAction = true;
		connection.enableWalk(false);
	}

	public static ZidestoreSpider getInstance() {
		return selfInstance;
	}

	public void startSpider(boolean runAsDeamon) {
		SpiderThread thread = new SpiderThread();

		if (runAsDeamon) {
			thread.setPriority(Thread.MIN_PRIORITY);
			//thread.setDaemon(true);
			thread.start();
		}
		else
			thread.run();
	}

	public void runSpiderOnce() {
		SpiderThread thread = new SpiderThread();
		thread.runSpider();
	}

	private void checkFolder(DAVItem folder) {
		if (!Proxy.isOnline())
			return;

		if (folder != null && folder.isFolder()) {
			try {
				//System.out.println("checking folder: " + folder.getLocation());

				//get Proxy instance
				Proxy proxy = Proxy.getInstance();
				URL url = new URL(folder.getLocation());

				//To update a folder ask the Proxy for the folder
				//proxy.getFolder(url.getPath());
			  CacheManager.getInstance().putFolder(folder);

				//CacheManager.getInstance().putFolder(proxy.getFolder(url.getPath()));

				//Only getIDsAndVersions necessary
				//The Proxy checks the items itselfes

				proxy.getIDsAndVersions(url.getPath());
			}
			catch (Exception e) {
				e.printStackTrace();
			}

		}
	}

	public static boolean isSpiderRunning() {
		return spiderRunning;
	}

	/**
	 * 
	 * @author sell
	 */
	class SpiderThread extends Thread {
		private int interval = 5;

		public SpiderThread() {
			try {
				interval =
					new Integer(ZSPConfig.getProperty("spider_interval")).intValue();
			}
			catch (Exception e) {
			}

			if (interval < 0)
				interval = 5;
			if (interval > 120)
				interval = 120;
		}

		final void runSpider() {
			if (spiderRunning) {
				System.out.println("Spider already running...skipping");
				return;
			}

			if (!Proxy.isOnline()) {
				System.out.println("Not in online mode...skipping");
				return;
			}

			if (CacheManager.isClearingCache()) {
				System.out.println("Clearing cache...skipping");
			}

			if (abortCurrentAction) {
				System.out.println("Abort requested");
				abortCurrentAction = false;
				return;
			}

			System.out.println("setting spiderRunning = true (1)");
			spiderRunning = true;
			connection.enableWalk(true);
			try {
				//System.out.println("vor walk");
				DAVItem rootFolder =
					connection.getFolderAttribs(
						ZSPConfig.getProperty("zidestore_url")
							+ "zidestore/so/"
							+ ZSPConfig.getProperty("zidestore_user")
							+ "/");

				rootFolder.setFolder(true);
				checkFolder(rootFolder);

				//System.out.println(rootFolder);
				connection.walkTroughFolders(
					ZSPConfig.getProperty("zidestore_url")
						+ "zidestore/so/"
						+ ZSPConfig.getProperty("zidestore_user")
						+ "/");
				//System.out.println("nach walk");
			}
			catch (Exception e) {
				e.printStackTrace();
			}
			finally {
				spiderRunning = false;
			}
		}

		public void run() {
			while (!stopSpider) {
				if (Proxy.isOnline()) {
					runSpider();
				}

				if (interval > 0) {
					try {
						sleep(interval * 60000);
					}
					catch (Exception e) {
					}
				}
				else
					break;
			}
			try {
				this.destroy();
			}
			catch (Error e) {
				System.out.println("can't destroy");
			}
		}
	}
}
