import { ReactGA } from '@arcblock/ux/lib/withTracker';
import { GA_LAST_LOGIN_METHOD, GA_LAST_ROLE, GA_LAST_SOURCE_PROVIDER } from '@arcblock/ux/lib/withTracker/constant';

// 监听用户登录事件
export const gaLoginSuccessHandler = () => {
  /**
   * @type {import('@arcblock/ux/lib/withTracker/action/login').LoginSuccessEvent}
   */
  const loginSuccessEvent = {
    action: 'loginSuccess',
    provider: localStorage.getItem(GA_LAST_LOGIN_METHOD),
    success: true,
  };
  ReactGA.event(loginSuccessEvent.action, loginSuccessEvent);
};

/**
 *
 * @param {Error} error
 */
export const gaLoginFailedHandler = (error) => {
  /**
   * @type {import('@arcblock/ux/lib/withTracker/action/login').LoginFailedEvent}
   */
  const loginFailedEvent = {
    action: 'loginFailed',
    provider: localStorage.getItem(GA_LAST_LOGIN_METHOD),
    success: false,
    errorMessage: error.message,
  };
  ReactGA.event(loginFailedEvent.action, loginFailedEvent);
};

export const gaSwitchPassportSuccessHandler = (_result, _decrypt, session) => {
  const fromRole = localStorage.getItem(GA_LAST_ROLE);
  const toRole = session?.user?.role;
  const change = `${fromRole} -> ${toRole}`;
  /** @type {import('@arcblock/ux/lib/withTracker/action/switch-passport').SwitchPassportSuccessEvent} */
  const switchPassportSuccessEvent = {
    action: 'switchPassportSuccess',
    change,
    success: true,
  };
  ReactGA.event(switchPassportSuccessEvent.action, switchPassportSuccessEvent);
};

/**
 *
 * @param {Error} error
 */
export const gaSwitchPassportFailedHandler = (error) => {
  /** @type {import('@arcblock/ux/lib/withTracker/action/switch-passport').SwitchPassportFailedEvent} */
  const switchPassportFailedEvent = {
    action: 'switchPassportFailed',
    success: false,
    errorMessage: error.message,
  };
  ReactGA.event(switchPassportFailedEvent.action, switchPassportFailedEvent);
};

/**
 *
 * @param {any} _result
 * @param {Function} _decrypt
 * @param {import('../types').SessionProps} session
 */
/**
 *
 * @param {any} _result
 * @param {Function} _decrypt
 * @param {import('../types').SessionProps} session
 */
export const gaBindWalletSuccessHandler = (_result, _decrypt, session) => {
  /**
   * @type {import('@arcblock/ux/lib/withTracker/action/bind-wallet').BindWalletSuccessEvent} */
  const bindWalletEvent = {
    action: 'bindWalletSuccess',
    provider: session?.user?.sourceProvider,
    success: true,
  };
  ReactGA.event(bindWalletEvent.action, bindWalletEvent);
};

/**
 * @param {Error} error
 * @param {import('../types').User} user
 */
export const gaBindWalletFailedHandler = (error) => {
  /** @type {import('@arcblock/ux/lib/withTracker/action/bind-wallet').BindWalletFailedEvent} */
  const bindWalletFailedEvent = {
    action: 'bindWalletFailed',
    provider: localStorage.getItem(GA_LAST_SOURCE_PROVIDER),
    success: false,
    errorMessage: error.message,
  };

  ReactGA.event(bindWalletFailedEvent.action, bindWalletFailedEvent);
};
