import java.io.*;
import java.net.*;

public class CompanyServer implements Runnable {
	private ServerSocket serverSocket;
	private CardCompany company;
	private String fileName = "out";

	CompanyServer(int port, CardCompany company) {
		this.company = company;
		
		try { serverSocket = new ServerSocket(port); }
		catch (IOException e) { System.out.println("Unable to connect: " + e); }
		
		new Thread(this).start();
	}
	
	public void run() {
		try {
			for (;;) {
				Socket s = serverSocket.accept();
				CompanyConnectionHandler cch = new CompanyConnectionHandler(s,company);
			}
		}
		catch (IOException e) { System.out.println("Error on server: " + e); }
	}
	
	public void autoBackup(String fileName, int frequency) {
		CompanyBackUp cbu = new CompanyBackUp(fileName, company, frequency);
	}

	public static void main(String arg[]) {
		int port;
		CardCompany company;
		String fileName;
		
		try {
			port = (arg.length >= 1) ? Integer.parseInt(arg[0]) : 5000;
			fileName = (arg.length == 2) ? arg[1] : "out";	
			
			if (arg.length == 2) 
				company = CardCompany.load(arg[1]);
			else
				company = new CardCompany("<New Company>", 10000);
		
			CompanyServer cs = new CompanyServer(port, company);
			
			cs.autoBackup(fileName, 15000);
		}
		catch(Exception e) { 
			System.out.println("Usage: java CompanyServer [port] [filename]");
		}
	}
}

class CompanyBackUp implements Runnable {
	String fileName;
	CardCompany company;
	int frequency;
	
	CompanyBackUp(String fileName, CardCompany company, int frequency) {
		this.fileName = fileName;
		this.company = company;
		this.frequency = frequency;
		
		new Thread(this).start();
	}
	
	public void run() {
		try {
			for(;;) {
				Thread.sleep(frequency);
			
				FileOutputStream fout = new FileOutputStream(fileName);
				DataOutputStream dout = new DataOutputStream(fout);
				company.write(dout);
				dout.close();
			}
		}
		catch(InterruptedException e) { /* Should never occur */ }
		catch(IOException e) { System.out.println("Error saving file: " + fileName); }
	}
}
	
