import {
  defaultAvatar,
  defaultCardImage,
} from './constants.sjs';

function getImageUrl(url, prefix) {
  url = url || defaultAvatar;
  return url.length === 32 ? `${prefix}${url}` : url;
}

function getCardStyle(extInfo, imgSrcPrefix, count = 0) {
  const styles = [];
  const { certBackgroundUrl = '' } = extInfo || {};
  const url = certBackgroundUrl || defaultCardImage || '';
  styles.push(`backgroundImage:url(${getImageUrl(url, imgSrcPrefix)})`);
  if (count) styles.push(`width: calc(${1 / count * 100}%${count > 1 ? ' - 0.32rem' : ''})`);
  return styles.join(';');
}

function getCardList(list, certMap) {
  return list.map((item) => {
    const { certType } = item.extInfo || {};
    let certCardInfo = certMap[certType] || {};
    certCardInfo = { ...certCardInfo, certType };
    return { ...item, certCardInfo };
  });
}

function getHeaderStyle(extInfo, imgSrcPrefix) {
  const styles = [];
  const { certCodeBackgroundUrl } = extInfo || {};
  if (certCodeBackgroundUrl) {
    styles.push(`background-image:url(${getImageUrl(certCodeBackgroundUrl, imgSrcPrefix)})`);
  }
  return styles.join(';');
}

export default {
  getImageUrl,
  getCardList,
  getCardStyle,
  getHeaderStyle,
};
