package com.alterdekim.hearthhack.component;

import com.alterdekim.hearthhack.config.ServerConfig;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.LinkedList;
import java.util.List;

@Slf4j
@Component
public class GameServer {

    private int port;

    private ServerSocket serverSocket;

    private List<GameConnection> connections;

    @Autowired
    private ServerConfig serverConfig;

    @Scheduled(fixedDelay = 5000)
    private void start() {
        try {
            this.port = serverConfig.getGamePort();
            this.connections = new LinkedList<>();
            this.serverSocket = new ServerSocket(this.port);
            while(true) {
                Socket client = this.serverSocket.accept();
                log.info("New WOW Connection Established From {}", client.getInetAddress().toString());
                GameConnection c = new GameConnection(client);
                this.connections.add(c);
                c.start();
            }
        } catch (IOException e) {
            log.error(e.getMessage());
        }
    }

    public void stopListening() {
        connections.forEach(GameConnection::stopListeningAndDisconnect);
        try {
            serverSocket.close();
        } catch (IOException e) {
            log.error(e.getMessage());
        }
    }

    public void removeConnection(GameConnection c) {
        connections.remove(c);
    }
}
