// Collection of code snippets by Arne Vajhøj 
// (likely posted to comp.os.vms/INFO-VAX, INFO-TPU, MACRO32, eksperten.dk, newz.dk, LinkedIn or other place sometime between 1990 and now) 
package chat.simple.server;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;

public class ClientHandler extends Thread {
    private PrintWriter pw;
    private BufferedReader br;
    private Server srv;
    private String usr;
    public ClientHandler(Socket s, Server srv) throws IOException {
        pw = new PrintWriter(s.getOutputStream());
        br = new BufferedReader(new InputStreamReader(s.getInputStream()));
        this.srv = srv;
        usr = "<no login>";
    }
    public void run() {
        String line;
        try {
            while((line = br.readLine()) != null) {
                if(line.startsWith("USR:")) {
                    usr = line.substring(4);
                } else if(line.startsWith("MSG:")) {
                    String msg = line.substring(4);
                    srv.sendAll(usr + ":" + msg);
                } else {
                    close();
                    return;
                }
            }
        } catch (IOException e) {
            close();
        }
    }
    public void send(String msg) {
        pw.println("MSG:" + msg);
        pw.flush();
    }
    private void close() {
        srv.removeClient(this);
        try {
            br.close();
            pw.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        System.out.println(usr + ":logout");
    }
}
