import { useEffect } from 'react';

import { encryptStorage } from 'src/config/encrypt-storage';
import { ReactNativeWebViewType } from 'src/types/login';

export const useMobileToken = (skipReadyMessaging = false) => {
  useEffect(() => {
    const handleMessage = (event: MessageEvent) => {
      if (event.data.type === 'humand') {
        encryptStorage.setItem('accessToken', event.data.token);
      }
    };

    window.addEventListener('message', handleMessage);
    const ReactNativeWebView = (window as ReactNativeWebViewType)
      .ReactNativeWebView;
    if (ReactNativeWebView) {
      ReactNativeWebView.postMessage('PAGE_RENDERED');
      if (!skipReadyMessaging) {
        ReactNativeWebView.postMessage('READY');
      }
    }

    return () => {
      window.removeEventListener('message', handleMessage);
    };
  }, []);
};
