import { storeAcknowledgements } from './acknowledgements';
import { FLARE_IFRAME_ID } from './constants';
import { Message, WebSocketHandler } from './webSocketHandler';

interface OpenLinkMessage {
  type: 'openLink';
  url: string;
}

export const postToWebView = (payload: any) => {
  const chatFrame = document.getElementById(
    FLARE_IFRAME_ID
  ) as HTMLIFrameElement;

  if (!chatFrame || !chatFrame.contentWindow) {
    throw new Error('Q Chat UI not mounted');
  }

  chatFrame.contentWindow.postMessage(payload, window.location.origin);
};

// Outbound commands
export function registerMessageListeners(
  socket: WebSocketHandler,
  container: Window
) {
  container.addEventListener('message', async (event: { data: Message }) => {
    const message = event.data;
    const command = message.command;
    const tabId = message.params?.tabId as string | undefined;

    switch (command) {
      case 'aws/chat/sendChatPrompt':
      case 'aws/chat/buttonClick':
      case 'aws/chat/listMcpServers':
      case 'aws/chat/mcpServerClick':
      case 'aws/chat/listConversations':
      case 'aws/chat/listRules':
      case 'aws/chat/conversationClick':
        try {
          const response = await socket.sendRequest({
            ...message,
            tabId
          });
          postToWebView(response);
          
        } catch(error){
          console.error(error)
        }
        break;
      case 'aws/chat/ready':
        socket.sendNotification(message);

        const chatOptionsEvent = {
          command: 'chatOptions',
          params: {
            mcpServers: true,
            history: true
          }
        };

        postToWebView(chatOptionsEvent);
        break;
      case 'aws/chat/tabAdd':
      case 'aws/chat/tabChange':
      case 'aws/chat/tabRemove':
      case 'aws/chat/pinnedContextAdd':
      case 'aws/chat/pinnedContextRemove':
      case 'aws/chat/createPrompt':
      case 'aws/chat/fileClick':
      case 'stopChatResponse':
      case 'aws/chat/openTab':
      case 'aws/chat/promptInputOptionChange':
         console.log(`Handling command - ${command} sending notification to websocket`);
        socket.sendNotification(message);
        break;
      case 'chatPromptOptionAcknowledged':
      case 'disclaimerAcknowledged':
        storeAcknowledgements(command);
        break;
      case 'aws/chat/linkClick':
      case 'aws/chat/infoLinkClick':
        // post a message to the iframe parent (SMUS app shell)
        // app shell will be responsible for opening the link
        const openLinkMessage: OpenLinkMessage = {
          type: 'openLink',
          url: message.params.link as string
        };
        window.parent.postMessage(openLinkMessage, '*');
        break;
      default:
        console.log(`Unhandled outbound command: ${command}`);
        break;
    }
  });
}
