package gltronic.voozik.web;

import java.io.IOException;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;

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.voozik.business.IRoomManager;

@Component
public class SocketHandler extends TextWebSocketHandler {
  private volatile List<WebSocketSession> sessions = new CopyOnWriteArrayList<>();

  @Autowired
  IRoomManager roomManager;

  @Override
  public void handleTextMessage(WebSocketSession session, TextMessage message) throws InterruptedException, IOException {
    System.err.println("[WS] message :" + message.getPayload());
    
    String payload = message.getPayload();
    JSONObject jsonObject = new JSONObject(payload);
    
    String type = (String) jsonObject.get("type");
    switch (type) {
      case "serverInfos":
        roomManager.sendServerInfos(session);
        break;
      case "login":
        roomManager.login(session, (String) jsonObject.get("name"));
        break;
      case "createRoom":
        roomManager.createRoom(session);
        break;
      case "connectRoom":
        roomManager.connectRoom(session, (String) jsonObject.get("name"));
        break;
      case "leave":
        roomManager.leave(session);
        break;
      case "offer":
      case "answer": 
      case "candidate":
        roomManager.followRTC(session, message);
        break;
      case "search":
        break;
      case "alive":
        break;
      default:
        roomManager.sendMessage(session, "error", "unknow command");
    }
  }

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

  @Override
  public void afterConnectionClosed(WebSocketSession session, CloseStatus closeStatus){
    System.err.println("[WS] connection closed");
    sessions.remove(session);
    roomManager.leave(session);
  }
}