package org.wikiwebserver.handler.iptocountry;

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

import org.wikiwebserver.core.interfaces.ConnectionHandler;
import org.wikiwebserver.core.interfaces.HandlerConfiguration;
import org.wikiwebserver.util.IPToCountry;

public class IPToCountryHandler implements ConnectionHandler {
    
    private Socket sock;
    private long startTime;
    private BufferedReader reader = null;
    private OutputStream out = null;

    public void handle(Socket sock) {
        this.startTime = System.currentTimeMillis();
        this.sock = sock;
        
        try {
            reader = new BufferedReader(new InputStreamReader(sock.getInputStream()));
            out = sock.getOutputStream();
            
            String line = reader.readLine();
            while (line != null) {
                String country = IPToCountry.getCountryName(line);
                if (country != null) {
                    out.write(country.getBytes());
                }
                line = reader.readLine();
            }
            
        } catch (IOException e) {
            // e.printStackTrace();
        } finally {
            forceClose();
        }
    }
    
    public void gracefulClose() {
        forceClose();
    }

    public void forceClose() {
        //  Close the connection, we are done
        try { out.close(); } catch (Exception ex) {}           
        try { reader.close(); } catch (Exception ex) {}  
        try { sock.close(); } catch (Exception ex) {}  
    }    

    public long getExecutionTime() {
        return System.currentTimeMillis() - startTime;
    }    

    public void forceStop() {
        forceClose();
        // Will always cause thread to stop
    }

    public void configure(HandlerConfiguration config) {

    }

}

