package org.ourfilesystem.com;

/*
 *  
    OurFileSystem is a peer2peer file sharing program.
    Copyright (C) 2012  Robert Gass

    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.,
    51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.

 */

import java.io.File;

import org.ourfilesystem.core.CoreComInterface;
import org.ourfilesystem.db.DataBaseComInterface;
import org.ourfilesystem.db.Peer;
import org.ourfilesystem.security.CryptoComInterface;

public class ComConnectionImpl implements ComConnectionInterface, Runnable {
	
	private boolean Closed;
	private CoreComInterface Core;
	private DataBaseComInterface DB;
	private CryptoComInterface Crypt;
	private SignatureRequestInterface SignatureRequest;
	private boolean Run;
	private File TempDir;
	private OFSServerSocket Server;
	private OFSConnector Connector;
	private boolean AutoSign;
	
	public ComConnectionImpl(CoreComInterface core, DataBaseComInterface db, CryptoComInterface crypt, SignatureRequestInterface req, String tmpdir, OFSServerSocket ss, OFSConnector con, boolean autosign) {
		AutoSign = autosign;
		Server = ss;
		Connector = con;
		SignatureRequest = req;
		Core = core;
		DB = db;
		Crypt = crypt;
		Run = true;
		TempDir = new File(tmpdir);
		TempDir.mkdirs();
		Closed = false;
		Thread t = new Thread(this);
		t.start();
	}
	
	public void Close() {
		if (!Closed) {
			Closed = true;
			try {
				if (Server != null) {
					Server.close();
				}
			}
			catch (Exception e) {
			}
		}
	}
	
	@Override
	public ComPeerInterface getComPeerInterface(Peer peer) {
		if (!Closed) {
			ComPeerImpl c = new ComPeerImpl(Core, DB, Crypt, SignatureRequest, peer, TempDir, AutoSign, Connector);
			return c;
		}
		return null;
	}

	public boolean isAutoSign() {
		return AutoSign;
	}

	@Override
	public void setAutoSign(boolean autoSign) {
		AutoSign = autoSign;
	}

	@Override
	public void run() {
		try {
			while (Run) {
				OFSSocket s = Server.accept();
				new ComPeerImpl(Core, DB, Crypt, SignatureRequest, null, TempDir, AutoSign, s);
				//We don't say we have a new connection until after the handshake completes successfully.
				//Core.newConnection(p);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}


}
