import { getNftBGColor, DEFAULT_COLORS, getNftBGColorFromDid, getSvg } from '@arcblock/nft-display';

export const getPassportColor = (preferredColor: string, did: string) => {
  let color;
  if (preferredColor === 'default') {
    color = DEFAULT_COLORS['app-passport'];
  } else if (preferredColor === 'auto') {
    color = getNftBGColorFromDid(did);
  } else {
    color = getNftBGColor(preferredColor);
  }

  return color;
};

export const getTextColor = (background: string) => {
  const r = parseInt(background.slice(1, 3), 16);
  const g = parseInt(background.slice(3, 5), 16);
  const b = parseInt(background.slice(5, 7), 16);
  const luminance = (0.299 * r + 0.587 * g + 0.114 * b) / 255;
  return luminance > 0.5 ? '#111' : '#EEE';
};

export const createPassportSvg = ({
  issuer = '',
  title = '',
  issuerDid = '',
  issuerAvatarUrl = '',
  ownerDid = '',
  ownerAvatarUrl = '',
  preferredColor = 'default',
  revoked = false,
  isDataUrl = false,
  width = '100%',
  height = '100%',
}) => {
  const color = getPassportColor(preferredColor, issuerDid);

  const svgXML = getSvg({
    width,
    height,

    tag: revoked ? 'revoked' : '',
    tagVariant: revoked ? 'error' : 'info',

    color,

    did: ownerDid,
    variant: 'app-passport',
    verifiable: true,

    issuer: {
      name: issuer,
      icon: issuerAvatarUrl,
    },

    header: {
      name: title,
      icon: ownerAvatarUrl,
    },

    // FIXME: @wangshijun this should be dynamic
    extra: {
      key: 'Exp',
      value: '2123-01-01',
    },
  });

  if (isDataUrl) {
    return `data:image/svg+xml;utf8,${encodeURIComponent(svgXML)}`;
  }

  return svgXML;
};

export const createKycSvg = ({
  issuer = '',
  title = '',
  issuerDid = '',
  issuerAvatarUrl = '',
  ownerDid = '',
  ownerName = '',
  ownerAvatarUrl = '',
  preferredColor = 'default',
  type = 'email',
  revoked = false,
  isDataUrl = false,
  width = '100%',
  height = '100%',
}) => {
  const color = getPassportColor(preferredColor, issuerDid);

  const svgXML = getSvg({
    width,
    height,

    tag: revoked ? 'revoked' : '',
    tagVariant: revoked ? 'error' : 'info',

    color,

    did: ownerDid,
    variant: 'app-kyc',
    verifiable: true,

    issuer: {
      name: issuer,
      icon: issuerAvatarUrl,
    },

    header: {
      name: ownerName,
      icon: ownerAvatarUrl,
    },

    extra: {
      key: type,
      value: title,
    },
  });

  if (isDataUrl) {
    return `data:image/svg+xml;utf8,${encodeURIComponent(svgXML)}`;
  }

  return svgXML;
};
