import { useEffect, useState } from 'react';

// following utils duplicate from: arcblock/blocklet-server/blocklet/meta/src/did
export function getPermanentDid(user) {
  return user?.did;
}

export function getConnectedAccounts(user) {
  return user?.connectedAccounts || user?.extraConfigs?.connectedAccounts || [];
}

export function getSourceProvider(user) {
  return user?.sourceProvider || user?.extraConfigs?.sourceProvider || 'wallet';
}

export function getSourceProviders(user) {
  const connectedAccounts = getConnectedAccounts(user);
  return connectedAccounts.map((item) => item.provider);
}

export function getConnectedDids(user) {
  const connectedAccounts = getConnectedAccounts(user);
  const didList = connectedAccounts.map((item) => item.did);
  return didList;
}

export function getWallet(user) {
  const connectedAccounts = getConnectedAccounts(user);
  const walletAccount = connectedAccounts.find((item) => item.provider === 'wallet');
  return walletAccount;
}
/**
 * @description
 * @export
 * @param {*} user
 * @return {string}
 */
export function getWalletDid(user) {
  const walletAccount = getWallet(user);
  return walletAccount?.did;
}

function useDid({ session }) {
  const [state, setState] = useState({
    did: '',
    wallet: '',
    walletDid: '',
    permanentDid: '',
    connectedDids: [],
    connectedAccounts: [],
    sourceProvider: '',
    sourceProviders: [],
  });
  useEffect(() => {
    if (session?.user) {
      const permanentDid = getPermanentDid(session.user);
      const walletDid = getWalletDid(session.user);
      const connectedAccounts = getConnectedAccounts(session.user);
      const connectedDids = getConnectedDids(session.user);
      const wallet = getWallet(session.user);
      const sourceProvider = getSourceProvider(session.user);
      const sourceProviders = getSourceProviders(session.user);

      setState({
        did: permanentDid,
        wallet,
        walletDid,
        permanentDid,
        connectedDids,
        connectedAccounts,
        sourceProvider,
        sourceProviders,
      });
    }
  }, [session?.user]);

  return state;
}

export default useDid;
