const { BlockletSource } = require('@blocklet/meta/lib/constants');

const getLogoFromLogoUrl = (blocklet) => {
  try {
    if (blocklet.source === BlockletSource.registry) {
      return new URL(blocklet.meta.logoUrl, blocklet.deployedFrom).href;
    }
    return blocklet.meta.logoUrl || null;
  } catch (error) {
    return null;
  }
};

const getBlockletLogo = ({ baseUrl, blocklet }) => {
  if (!baseUrl) {
    return getLogoFromLogoUrl(blocklet);
  }

  let logo = `${baseUrl}/images/blocklet.png`;
  try {
    if (blocklet.meta.logoUrl) {
      logo = getLogoFromLogoUrl(blocklet);
    } else if (blocklet.meta.logo) {
      logo = `${baseUrl}/blocklet/logo/${blocklet.meta.did}`;
    }
  } catch (err) {
    // Do nothing
  }

  return logo;
};

module.exports = {
  getBlockletLogo,
};
