package org.ourfilesystem.com;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

import net.i2p.I2PException;
import net.i2p.client.I2PSession;
import net.i2p.client.streaming.I2PServerSocket;
import net.i2p.client.streaming.I2PSocket;
import net.i2p.client.streaming.I2PSocketManager;
import net.i2p.client.streaming.I2PSocketManagerFactory;
import net.i2p.data.DataFormatException;
import net.i2p.data.PrivateKeyFile;

public class OFSI2PServerSocket implements OFSServerSocket {
	
	private I2PSocketManager Manager;
	private I2PServerSocket Server;

	public OFSI2PServerSocket(String kfn) throws IOException, DataFormatException {
		Manager = null;
		File f = new File(kfn);
		if (f.exists()) {
			FileInputStream fis = new FileInputStream(f);
			Manager = I2PSocketManagerFactory.createManager(fis);
			fis.close();
		}
		else {
			Manager = I2PSocketManagerFactory.createManager();
			PrivateKeyFile pkf = new PrivateKeyFile(f, Manager.getSession());
			pkf.write();
		}
		Server = Manager.getServerSocket();
	}
	
	public String getMyLocation() {
		I2PSession ses = Manager.getSession();
		return ses.getMyDestination().toBase64();
	}
	
	public OFSConnector getOFSConnector() {
		OFSI2PConnector con = new OFSI2PConnector(Manager);
		return con;
	}

		@Override
	public OFSSocket accept() throws IOException {
		try {
			I2PSocket sock = Server.accept();
			if (sock != null) {
				return new OFSI2PSocket(sock);
			}
		} catch (I2PException e) {
			e.printStackTrace();
			throw new IOException(e);
		}
		return null;
	}

	@Override
	public void close() throws IOException {
		try {
			Server.close();
		} catch (I2PException e) {
			e.printStackTrace();
			throw new IOException(e);
		}
	}

}
