package gltronic.voozik.business;

import java.io.IOException;

import org.json.JSONObject;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;

import gltronic.voozik.model.VRoom;

public class SocketUtils {
  public static void sendMessage(WebSocketSession session, String type, String message) {
    try {
      session.sendMessage(new TextMessage("{\"type\":\"" + type + "\",\"message\": \"" + message.toString() + "\" }"));
    } catch (IOException e) {
      e.printStackTrace();
    }
  }

  public static void forwardMessage(WebSocketSession session, String type, JSONObject message) {
    try {
      session.sendMessage(new TextMessage("{\"type\":\"" + type + "\",\"message\": " + message.toString() + " }"));
    } catch (IOException e) {
      e.printStackTrace();
    }
  }

  public static void broadcast(VRoom room, String type, JSONObject message) {
    room.getUsers().forEach(user -> {
      forwardMessage(user.getSession(), type, message);
    });
  }
}