package gltronic.tronio.web;

import java.io.IOException;

import com.fasterxml.jackson.databind.ObjectMapper;

import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

import gltronic.tronio.business.IGameManager;
import gltronic.tronio.business.SocketUtils;
import gltronic.tronio.model.Player;

@Component
public class SocketHandler extends TextWebSocketHandler {

  @Autowired
  IGameManager gameManager;

  @Override
  public void handleTextMessage(WebSocketSession session, TextMessage message)
      throws InterruptedException, IOException {
    // System.err.println("[WS] message :" + message.getPayload());

    String payload = message.getPayload();
    JSONObject rootObject = new JSONObject(payload);

    String type = rootObject.getString("type");
    switch (type) {
      case "update":
        Player player = new ObjectMapper().readValue(rootObject.get("message").toString(), Player.class);

        gameManager.updatePlayer(session, player);
        break;
      default:
        SocketUtils.sendMessage(session, "error", "unknow command");
    }
  }

  @Override
  public void afterConnectionEstablished(WebSocketSession session) throws Exception {
    System.err.println("[WS] new connection " + this);
    gameManager.login(session);
  }

  @Override
  public void afterConnectionClosed(WebSocketSession session, CloseStatus closeStatus) {
    System.err.println("[WS] connection closed");
    try {
      gameManager.leave(session);
    } catch (InterruptedException | IOException e) {
      e.printStackTrace();
    }
  }
}
