import io from 'socket.io-client';
import Socket = SocketIOClient.Socket;
let socket: Socket | null = null;

function initializeSocket(token: string): Socket | null {
  // Only initialize if we don't already have a socket
  if (!socket && token) {
    socket = io({
      auth: {
        token: token,
      },
    });

    socket.on('connect', () => console.log('connected'));

    socket.on('disconnect', () => {
      console.log('Disconnected from server');
    });
  }
  return socket;
}

function sendMessage(message: string, recipient: string | null) {
  if (!socket) {
    console.error('Socket not initialized');
    return;
  }

  socket.emit('chat message', {
    message: message,
    recipient: recipient,
  });

  console.log('sent message: ', {
    message: message,
    recipient: recipient,
  });
}

type Contact = {
  contact: string;
  read: boolean;
};

function sendContact(data: Contact) {
  if (!socket) {
    console.error('Socket not initialized');
    return;
  }

  const { contact, read } = data;
  socket.emit('add contact', { contact: contact, read: read });
  console.log('Sent contact: ', contact, 'status: ', read);
}

function sendRequestHistoricalMessages(recipient: string) {
  if (!socket) {
    console.error('Socket not initialized');
    return;
  }

  socket.emit('historical messages', { recipient: recipient });
  console.log('Requested historical messages for: ', recipient);
}

function sendRequestContactsList() {
  if (!socket) {
    console.error('Socket not initialized');
    return;
  }

  socket.emit('get contacts list');
  console.log('Requested contact list');
}
export {
  initializeSocket,
  sendMessage,
  sendContact,
  sendRequestHistoricalMessages,
  sendRequestContactsList,
  socket,
};
