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

class CompanyConnectionHandler implements Runnable {
	private Socket socket;
	private DataInputStream din;
	private DataOutputStream dout;
	private CardCompany company;

	CompanyConnectionHandler(Socket socket, CardCompany company) {
		this.socket = socket;
		this.company = company;
		
		try {
			din = new DataInputStream(socket.getInputStream());
			dout = new DataOutputStream(socket.getOutputStream());
			new Thread(this).start();
		}
		catch (IOException e) {	System.out.println("Error starting connection"); }
	}
	
	public void run() {
		try {
			boolean isMore = true;
			Card c;
			
			while(isMore) {				
				CompanyRequest rq = new CompanyRequest(din);
				CompanyResponse rs = null;

				switch(rq.getType()) {
					case CompanyRequest.ISSUE:
						c = company.issueCard(rq.getName());
						rs = new CompanyResponse(c);
						break;
						
					case CompanyRequest.FIND_BY_NAME:
						c = company.findCard(rq.getName());
						rs = new CompanyResponse(c);
						break;
							
					case CompanyRequest.FIND_BY_NUMBER:
						c = company.findCard(rq.getNumber());
						rs = new CompanyResponse(c);
						break;	
						
					case CompanyRequest.CANCEL:
						boolean status = company.cancelCard(rq.getNumber());
						rs = new CompanyResponse(status);
						break;
												
					case CompanyRequest.PURCHASE:
						c = company.purchase(rq.getNumber(), rq.getItem(), rq.getAmount());
						rs = new CompanyResponse(c);
						break;
						
					case CompanyRequest.PAYMENT:
						c = company.payment(rq.getNumber(), rq.getAmount());
						rs = new CompanyResponse(c);
						break;
						
					case CompanyRequest.HANG_UP:
						rs = new CompanyResponse(true);
						isMore = false;
						break;
						
					default:
						System.out.println("Invalid Request");
				}
				
				rs.write(dout);
			}
		}
		catch(IOException e) { System.out.println("IO Exception processing request: " + e); }
	
		try {	socket.close(); }
		catch(IOException e) { /* Do Nothing */ }
	}
}
	
