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

public class NetworkCompanyProxy implements CompanyTransactionProxy {
	private String host;
	private int port;
	private Socket socket;
	private DataInputStream in;
	private DataOutputStream out;

	public NetworkCompanyProxy(String host, int port) {
		this.host = host;
		this.port = port;
	}
	
	public boolean connect() {
		try {
			socket = new Socket(host, port);
			in = new DataInputStream(socket.getInputStream());
			out = new DataOutputStream(socket.getOutputStream());
			return true;
		}
		catch (IOException e) { return false; }
	}
	
	public boolean disconnect() {
		try {
			socket.close();
			return true;
		}
		catch (IOException e) { return false; }
	}
	
	private CompanyResponse processRequest(CompanyRequest rq) {
		CompanyResponse rs;
		
		try {		
			rq.write(out);		
			rs = new CompanyResponse(in);			
		}
		catch(IOException e) {
			rs = new CompanyResponse(false);
		}
		
		return rs;
	}
	
	public Card issueCard(String name) {		
		CompanyResponse rs = processRequest(CompanyRequest.createIssueRequest(name));		
		return rs.getCard();
	}
	
	
	public boolean cancelCard(int number) {
		CompanyResponse rs = processRequest(CompanyRequest.createCancelRequest(number));
		return rs.getStatus();
	}

	public Card purchase(int number, String item, double amount) {
		CompanyResponse rs = processRequest(CompanyRequest.createPurchaseRequest(number, item, amount));
		return rs.getCard();
	}

	public Card payment(int number, double amount) {
		CompanyResponse rs = processRequest(CompanyRequest.createPaymentRequest(number, amount));
		return rs.getCard();
	}

	public Card findCard(String name) {
		CompanyResponse rs = processRequest(CompanyRequest.createFindRequest(name));
		return rs.getCard();
	}

	public Card findCard(int number) {
		CompanyResponse rs = processRequest(CompanyRequest.createFindRequest(number));
		return rs.getCard();
	}
}
