/*
 * 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.UPnPManager;
import com.limegroup.gnutella.Uploader;
import com.limegroup.gnutella.downloader.ManagedDownloader;
import com.limegroup.gnutella.gui.DaapManager;
import com.limegroup.gnutella.io.NIODispatcher;
import com.limegroup.gnutella.settings.ConnectionSettings;
import com.limegroup.gnutella.settings.DaapSettings;
import com.limegroup.gnutella.util.CommonUtils;
import com.limegroup.gnutella.util.FileUtils;
import com.limegroup.gnutella.util.I18NConvert;

public class AqMain {

	/* Instances */

	private static String javaBundlePath;

	protected static InputStreamReader reader = null;

	protected static OutputStreamWriter writer = null;

	/* State */

	protected static boolean shouldShutdown = false;

	/* Main */

	public static void main(String[] args) {

		Thread.currentThread().setPriority(Thread.MIN_PRIORITY);

		javaBundlePath = args[0];
		if (javaBundlePath.startsWith("\""))
			javaBundlePath = javaBundlePath.substring(1, javaBundlePath
					.length() - 1);

		ConnectionSettings.USE_NIO.setValue(args[1].equals("1"));
		DaapSettings.DAAP_USE_NIO.setValue(args[1].equals("1"));

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

		/* make writable app support directories */

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

		/* set error callback */

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

		/* check personal firewall blocking */

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

		/* read loop */

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

	}

	protected static void startup() {

		/* start UPnP */

		if (CommonUtils.isJava14OrLater()
				&& !ConnectionSettings.DISABLE_UPNP.getValue())
			UPnPManager.instance().start();

		/* start LW */

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

		/* start DAAP */

		if (CommonUtils.isJava14OrLater()
				&& DaapSettings.DAAP_ENABLED.getValue()) {
			try {
				DaapManager.instance().start();
				DaapManager.instance().init();
			} catch (IOException e) {
				DaapSettings.DAAP_ENABLED.setValue(false);
				e.printStackTrace();
			}
		}

		/* 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();
		}
	}

	public static void shutdown() {

		/* close streams */

		try {
			if (reader != null)
				reader.close();
			if (writer != null) {
				synchronized (writer) {
					writer.close();
				}
			}
		} catch (IOException e) {
			e.printStackTrace();
		}

		System.exit(0);
	}

	public static String getJavaBundlePath() {
		return javaBundlePath;
	}

}

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

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

}
