/***********************************************************************

GECCO, a platform for command and control gaming

Copyright (C) 2001 Henrik Bäärnhielm, Andreas Enblom, Niklas
Hallenfur, Karl Hasselström, Henrik Hägerström, Oskar Linde, Jing Fu
Zi and Jon Åslund

This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or (at
your option) any later version.

This program is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307,
USA.

***********************************************************************/

package gecco.communication.server;
import gecco.communication.messages.*;
import java.awt.*;

import java.io.*;
import java.net.*;
import java.util.*;
import java.util.Map;

/**
 *  A class that will listen for incoming connections from clients, and handle
 *  the initial communication, until the client successfully joins as a role,
 *  and calls startGame. all communication with the client will thereafter be
 *  handled by a DataExchangeHandler
 *
 * @author     Niklas Hallenfur, Jon Åslund
 * @created    June 27, 2001
 */

class NewClientListener implements Runnable {

    /*
     * to be removed in iteration 2
     */
    /**
     *  Description of the Field
     */
    private DataInputStream data_in;
    /**
     *  Description of the Field
     */
    private DataOutputStream data_out;

    /**
     *  Description of the Field
     */
    private ClientAmbassador started_by;
    /**
     *  Description of the Field
     */
    private ServerSocket server;


    /**
     * @param  port             The port where to listen for incoming
     *      connections
     * @param  s                Description of Parameter
     * @exception  IOException  Description of Exception
     */

    public NewClientListener(ClientAmbassador s, int port) throws IOException {
        started_by = s;
        try {
            server = new ServerSocket(port);
        } catch (IOException e) {
            System.out.println("NewClientListener(): Could not create ServerSocket");
            throw e;
        }
    }


    /**
     *  to be removed in iteration 2
     */

    /*
     * private StringTokenizer getTokenizedInput() throws IOException {
     * return new StringTokenizer(readString());
     * return new StringTokenizer(data_in.readUTF());
     * }
     */

    public void run() {
        while (true) {
            String role = null;
            // som vilken roll vill klient ansluta?
            try {
                StringTokenizer st;
                Socket s = accept();
                // vänta på klienter
                boolean handshake = true;

                while (handshake) {

                    int command = data_in.readInt();

                    switch (command) {

                        case MessageType.disconnect:
                            handshake = false;
                            break;
                        case MessageType.getAvailableRoles:
                            sendAvailableRoles(s);
                            break;
                        case MessageType.joinAsRole:
                            role = data_in.readUTF();
                            connectToKrigsspel(s, role);
                            break;
                        case MessageType.getMapSize:
                            sendMapSize();
                            break;
                        case MessageType.getMap:
                            sendMap();
                            break;
                        case MessageType.startGame:
                            startGame(s, role);
                            handshake = false;
                    }

                }

            } catch (Exception e) {
            }
        }
    }



    /*
     * vänta på anslutning och hämta en InputStream
     */

    /**
     *  Description of the Method
     *
     * @return    Description of the Returned Value
     */
    public Socket accept() {
        try {
            Socket s = server.accept();

            data_in = new DataInputStream(s.getInputStream());
            data_out = new DataOutputStream(s.getOutputStream());

            return s;
        } catch (Exception e) {
            return null;
        }

    }


    /**
     *  sends the size of the map
     *
     * @exception  Exception  Description of Exception
     */
    public void sendMapSize() throws Exception {
        try {
            Dimension d = started_by.getMapSize();
            data_out.writeInt(d.width);
            data_out.writeInt(d.height);
            data_out.flush();
        } catch (Exception e) {
            throw e;
        }
    }


    /**
     *  sends the whole map
     *
     * @exception  Exception  Description of Exception
     */
    public void sendMap() throws Exception {
        try {
            byte[] mapRGB = started_by.getMap();
            // Write the whole map to the socket!
            data_out.write(mapRGB);

            Map icons = started_by.getUnitTypeIcons();
            Iterator types = icons.keySet().iterator();

            data_out.writeInt(icons.size());

            while (types.hasNext()) {

                String type = (String) types.next();
                byte[] icon = (byte[]) icons.get(type);
                data_out.writeUTF(type);
                data_out.writeInt(icon.length);
                data_out.write(icon);
            }

            data_out.flush();
        } catch (Exception e) {
            throw e;
        }
    }


    /**
     *  Description of the Method
     *
     * @param  s              Description of Parameter
     * @exception  Exception  Description of Exception
     */
    private void sendAvailableRoles(Socket s) throws Exception {
        data_out.writeUTF(started_by.rolesLeft());
        data_out.flush();
    }


    /**
     *  to be modified in iteration 2
     *
     * @param  s     Description of Parameter
     * @param  role  Description of Parameter
     * @return       Description of the Returned Value
     */

    private boolean connectToKrigsspel(Socket s, String role) {

        try {
            /*
             * kolla om klienten får vara den rollen
             */
            if (!started_by.acceptRole(role)) {
                data_out.writeBoolean(false);
                data_out.flush();
                return false;
            } else {
                data_out.writeBoolean(true);
                return true;
            }
        } catch (IOException ioe) {
        }
        return false;
    }


    /**
     *  Description of the Method
     *
     * @param  s     Description of Parameter
     * @param  role  Description of Parameter
     */
    private void startGame(Socket s, String role) {
        try {
            int id = started_by.getAvailableId(role);

            /*
             * skapa en ny ClientConnection och lägg till
             */
            ClientConnection c = new ClientConnection(s, role, id);
            started_by.addClient(c);
        } catch (Exception e) {
        }
    }

}

