/*
 * Copyright (c) 2002-2004 David Keiichi Watanabe
 * davew@xlife.org
 *
 * Modified by (c) 2004-2005 heavy_baby
 * heavy_baby@users.sourceforge.jp
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 */

package jp.sourceforge.cabos;

import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;

import com.limegroup.gnutella.Downloader;
import com.limegroup.gnutella.ErrorService;
import com.limegroup.gnutella.MessageService;
import com.limegroup.gnutella.RouterService;
import com.limegroup.gnutella.Uploader;
import com.limegroup.gnutella.downloader.ManagedDownloader;
import com.limegroup.gnutella.io.NIODispatcher;
import com.limegroup.gnutella.settings.ApplicationSettings;
import com.limegroup.gnutella.util.CommonUtils;
import com.limegroup.gnutella.util.FileUtils;

public class AqMain {
	/* Instances */

	private static InputStreamReader reader = null;

	private static OutputStreamWriter writer = null;

	/* State */

	protected static boolean shouldShutdown = false;

	/* Main */

	public static void main(String[] args) {
		/* open streams */

		System.err.println(System.getProperty("os.name"));
		System.err.println(System.getProperty("os.version"));
		System.err.println(System.getProperty("java.name"));
		System.err.println(System.getProperty("java.version"));
		System.err.println(System.getProperty("jvm.name"));
		System.err.println(System.getProperty("jvm.version"));
		System.err.println(System.getProperty("os.language"));
		System.err.println(System.getProperty("os.country"));
		try {
			reader = new InputStreamReader(System.in, "UTF-8");
			writer = new OutputStreamWriter(System.out, "UTF-8");
		} catch (Exception e) {
			e.printStackTrace();
			System.exit(0);
		}
		AqEvent.signalEvent(AqEvent.kLWEventCoreConnected);

		/* set error callback */

		AqEventHandler handler = new AqEventHandler();
		ErrorService.setErrorCallback(handler);
		MessageService.setCallback(handler);

		/* make writable app support directories */

		if (CommonUtils.getUserHomeDir().exists())
			FileUtils.setWriteable(CommonUtils.getUserHomeDir());
		if (CommonUtils.getUserSettingsDir().exists())
			FileUtils.setWriteable(CommonUtils.getUserSettingsDir());

		/* check personal firewall blocking */

		if (!NIODispatcher.instance().isRunning())
			shutdown();

		/* read loop */

		AqEvent.signalEvent(AqEvent.kLWEventCoreSettingRequest);
		readLoop();
		RouterService.shutdown();
		shutdown();

	}

	protected static void startup() {
		/* start LW */

		RouterService router = new RouterService((AqEventHandler) ErrorService
				.getErrorCallback());
		router.start();

		/* schedule threads */

		RouterService.schedule(new DownloadRetry(), 120 * 60 * 1000,
				120 * 60 * 1000);
		RouterService.schedule(new ConnectionUpdate(), 60 * 1000, 60 * 1000);
		RouterService.schedule(new TransferUpdate(), 1 * 1000, 1 * 1000);

		AqEvent.signalEvent(AqEvent.kLWEventCoreInitialized);
	}

	private static void readLoop() {

		int b;
		List args = new LinkedList();
		StringBuffer fragment = new StringBuffer();

		try {

			while (!shouldShutdown && (b = reader.read()) != -1) {
				char c = (char) b;

				if (c == '|' || c == '\n') {
					args.add(fragment.toString());
					fragment.setLength(0);

					if (c == '\n') {
						try {
							AqDispatcher.dispatchCommand(args);
						} catch (Exception e) {
							e.printStackTrace();
						}
						args.clear();
					}

				} else {
					fragment.append(c);
				}
			}

		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	protected static void writeEvent(String event) {
		synchronized (writer) {
			try {
				writer.write(event);
				writer.write("\n");
				writer.flush();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	protected static void shutdown() {
		synchronized (writer) {
			try {
				reader.close();
				writer.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		System.exit(0);
	}
}

/* DownloadRetry */

class DownloadRetry implements Runnable {

	public void run() {
		/* Downloads */

		try {
			for (Iterator i = AqEventHandler.downloads.iterator(); i.hasNext(); retryDownload((ManagedDownloader) i
					.next()))
				;
		} catch (Exception e) {
		}
	}

	private void retryDownload(ManagedDownloader d) {
		if (d != null && d.getState() == Downloader.WAITING_FOR_USER)
			d.resume();
	}

}

/* ConnectionUpdate */

class ConnectionUpdate implements Runnable {
	public void run() {
		AqEvent.signalEvent(AqEvent.kLWEventConnectionsUpdated);
	}
}

/* TransferUpdate */

class TransferUpdate implements Runnable {

	public void run() {
		/* Downloads */

		try {
			for (Iterator i = AqEventHandler.downloads.iterator(); i.hasNext(); publishUpdate((ManagedDownloader) i
					.next()))
				;
		} catch (Exception e) {
		}
		AqEvent.signalEvent(AqEvent.kLWEventDownloadsUpdated);

		/* Uploads */

		try {
			for (Iterator i = AqEventHandler.uploads.iterator(); i.hasNext(); publishUpdate((Uploader) i
					.next()))
				;
		} catch (Exception e) {
		}
		AqEvent.signalEvent(AqEvent.kLWEventUploadsUpdated);

		/* calculate timer */

		int totalUptime = ApplicationSettings.TOTAL_UPTIME.getValue() + 1;
		ApplicationSettings.TOTAL_UPTIME.setValue(totalUptime);
		ApplicationSettings.AVERAGE_UPTIME.setValue(totalUptime
				/ ApplicationSettings.SESSIONS.getValue());
	}

	private void publishUpdate(ManagedDownloader d) {
		if (d != null)
			AqEvent.signalEvent(AqEvent.kLWEventUpdateDownloadStats, d);
	}

	private void publishUpdate(Uploader u) {
		if (u != null)
			AqEvent.signalEvent(AqEvent.kLWEventUpdateUploadStats, u);
	}

}
