/*
 * Copyright (c) 2002-2004 David Keiichi Watanabe
 * davew@xlife.org
 *
 * Modified by (c) 2004-2008 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.io.UnsupportedEncodingException;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.limegroup.gnutella.Downloader;
import com.limegroup.gnutella.RouterService;
import com.limegroup.gnutella.UPnPManager;
import com.limegroup.gnutella.downloader.ManagedDownloader;
import com.limegroup.gnutella.io.NIODispatcher;
import com.limegroup.gnutella.settings.ApplicationSettings;
import com.limegroup.gnutella.settings.ConnectionSettings;
import com.limegroup.gnutella.util.CommonUtils;
import com.limegroup.gnutella.util.FileUtils;

public class AqMain {
	/* Instances */

	private static final Log LOG = LogFactory.getLog(AqMain.class);

	private static InputStreamReader reader = null;

	private static OutputStreamWriter writer = null;

	private static boolean isShuttingdown = 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 (UnsupportedEncodingException e) {
			System.exit(0);
		}

		/* check jvm version */

		if (!CommonUtils.isJava14OrLater())
			System.exit(0);

		AqEvent.signalEvent(AqEvent.kLWEventCoreConnected);

		/* make writable app support directories */

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

		/* check personal firewall blocking */

		if (!NIODispatcher.instance().isRunning())
			System.exit(0);

		/* read loop */

		AqEvent.signalEvent(AqEvent.kLWEventCoreInitialized);

		readLoop();
		System.exit(0);
	}

	private static void readLoop() {

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

		while (!isShuttingdown) {
			int b;
			try {
				b = reader.read();
			} catch (IOException e) {
				LOG.error(e);
				break;
			}
			char c = (char) b;

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

				if (c == '\n' || c == '\r') {
                    try {
                        AqDispatcher.dispatchCommand(args);
                    } catch (Throwable t) {
                        LOG.error(t);
                        break;
                    }
					args.clear();
				}

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

	}

	protected static void start() {
		/* start UPnP */

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

		/* start LW */

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

		/* schedule threads */

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

	protected static void writeEvent(String event) {
		synchronized (writer) {
			try {
				writer.write(event);
				writer.flush();
			} catch (IOException e) {
				LOG.error(e);
			}
		}
	}

	protected static void shutdown() {
		synchronized (writer) {
			try {
				reader.close();
				writer.close();
			} catch (IOException e) {
				LOG.error(e);
			}
		}
		isShuttingdown = true;
	}
}

/* ConnectionUpdate */

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

/* TransferUpdate */

class TransferUpdate implements Runnable {

	public void run() {
		/* calculate timer */

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

		/* Downloads */

		for (Iterator i = RouterService.getDownloadManager().getDownloads(); i
				.hasNext(); AqEvent.signalEvent(
				AqEvent.kLWEventUpdateDownloadStats, i.next()))
			;
		AqEvent.signalEvent(AqEvent.kLWEventDownloadsUpdated);

		/* Uploads */

		for (Iterator i = RouterService.getUploadManager().getUploads(); i
				.hasNext(); AqEvent.signalEvent(
				AqEvent.kLWEventUpdateUploadStats, i.next()))
			;
		AqEvent.signalEvent(AqEvent.kLWEventUploadsUpdated);
	}
}

/* DownloadRetry */

class DownloadRetry implements Runnable {

	public void run() {
		/* Downloads */
		
		for (Iterator i = RouterService.getDownloadManager().getDownloads(); i
		.hasNext(); ) {
			ManagedDownloader d = (ManagedDownloader)i.next();
			if (d.getState() == Downloader.WAITING_FOR_USER)
				d.resume();
		}
	}
}
