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 */

		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);
	}

}
