import get from 'lodash/get';
import isEmpty from 'lodash/isEmpty';
import isObject from 'lodash/isObject';
import store from '@state/store';

// use local storage for messaging. Set message in local storage and clear it right away
// This is a safe way how to communicate with other tabs while not leaving any traces
//

function messageBroadcast(message: unknown): void {
  localStorage.setItem('microws', JSON.stringify(message));

  localStorage.removeItem('microws');
}

function messageReceive(e: StorageEvent): void {
  let message;
  const key = e.key;

  if (key !== 'microws') {
    return; // ignore other keys
  }

  try {
    message = e.newValue ? JSON.parse(e.newValue) : '';
  } catch (e) {
    console.warn(`[broadcast][messageReceive] error: ${e}`);
  }

  if (isEmpty(message)) {
    return; // ignore empty msg or msg reset
  }

  if (isObject(message)) {
    for (const [key] of Object.entries(message)) {
      const action = get(message, `${key}.action`);

      if (action) {
        switch (action) {
          case 'relogin': {
            setTimeout(() => {
              store.dispatch('oidcClient/logoutOidcClient');
            }, 1000); // вкладка-инициатор выхода должна быть первой, поэтому тут задержка

            break;
          }
        }
      }
    }
  }
}

export { messageReceive, messageBroadcast };
