import { useAgent } from '@aries-framework/react-hooks';
import { getProofData, groupSharedProofDataByCredential } from '@hyperledger/aries-bifold-verifier';
import { Attribute, Predicate } from '@hyperledger/aries-oca/build/legacy';
import React, { useEffect, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { useWindowDimensions, Image, StyleSheet, Text, View } from 'react-native';
import { useAnimatedComponents } from '../../contexts/animated-components';
import { useConfiguration } from '../../contexts/configuration';
import { useTheme } from '../../contexts/theme';
import { toImageSource } from '../../utils/credential';
import { formatIfDate, pTypeToText } from '../../utils/helpers';
import { buildFieldsFromSharedAnonCredsProof } from '../../utils/oca';
import { testIdWithKey } from '../../utils/testable';
import { AttributeValue } from '../record/RecordField';
const SharedDataCard = _ref => {
  var _overlay$bundle, _overlay$bundle2;
  let {
    sharedData
  } = _ref;
  const {
    ColorPallet,
    TextTheme
  } = useTheme();
  const {
    OCABundleResolver
  } = useConfiguration();
  const {
    i18n
  } = useTranslation();
  const {
    width
  } = useWindowDimensions();
  const logoHeight = width * 0.12;
  const padding = width * 0.05;
  const borderRadius = 10;
  const styles = StyleSheet.create({
    container: {
      marginBottom: 20,
      backgroundColor: ColorPallet.grayscale.white,
      borderRadius: borderRadius
    },
    cardContainer: {
      flexDirection: 'row',
      minHeight: 0.33 * width
    },
    cardColorContainer: {
      width: logoHeight,
      borderTopLeftRadius: borderRadius,
      borderBottomLeftRadius: borderRadius
    },
    logoContainer: {
      top: padding,
      left: -1 * logoHeight + padding,
      width: logoHeight,
      height: logoHeight,
      backgroundColor: ColorPallet.grayscale.white,
      borderRadius: 8,
      justifyContent: 'center',
      alignItems: 'center',
      elevation: 5
    },
    cardAttributes: {
      width: '65%',
      paddingTop: 20,
      paddingBottom: 10
    },
    attributeContainer: {
      marginBottom: 10
    },
    attributeName: {
      fontSize: 16,
      fontWeight: 'normal',
      color: ColorPallet.grayscale.black
    },
    attributeValue: {
      fontSize: 18,
      fontWeight: 'bold',
      color: ColorPallet.grayscale.black
    }
  });
  const [overlay, setOverlay] = useState(undefined);
  const attributeTypes = overlay === null || overlay === void 0 ? void 0 : (_overlay$bundle = overlay.bundle) === null || _overlay$bundle === void 0 ? void 0 : _overlay$bundle.captureBase.attributes;
  const attributeFormats = overlay === null || overlay === void 0 ? void 0 : (_overlay$bundle2 = overlay.bundle) === null || _overlay$bundle2 === void 0 ? void 0 : _overlay$bundle2.bundle.attributes.map(attr => {
    return {
      name: attr.name,
      format: attr.format
    };
  }).reduce((prev, curr) => {
    return {
      ...prev,
      [curr.name]: curr.format
    };
  }, {});
  useEffect(() => {
    const attributes = buildFieldsFromSharedAnonCredsProof(sharedData.data);
    const params = {
      identifiers: {
        credentialDefinitionId: sharedData.identifiers.cred_def_id,
        schemaId: sharedData.identifiers.schema_id
      },
      language: i18n.language,
      attributes
    };
    OCABundleResolver.resolveAllBundles(params).then(bundle => {
      setOverlay(bundle);
    });
  }, [sharedData]);
  const CardField = _ref2 => {
    var _parsedPredicate, _parsedPredicate2;
    let {
      item
    } = _ref2;
    const {
      t
    } = useTranslation();
    let parsedPredicate = undefined;
    if (item instanceof Predicate) {
      parsedPredicate = pTypeToText(item, t, attributeTypes);
      parsedPredicate.pValue = formatIfDate(attributeFormats[item.name ?? ''], parsedPredicate.pValue);
    } else {
      ;
      item.value = formatIfDate(attributeFormats[item.name ?? ''], item.value);
    }
    return /*#__PURE__*/React.createElement(View, {
      key: item.name,
      style: [styles.attributeContainer]
    }, /*#__PURE__*/React.createElement(Text, {
      style: styles.attributeName
    }, item.label || item.name), item instanceof Attribute && /*#__PURE__*/React.createElement(AttributeValue, {
      style: styles.attributeValue,
      field: item,
      shown: true
    }), item instanceof Predicate && /*#__PURE__*/React.createElement(Text, {
      style: styles.attributeValue
    }, `${(_parsedPredicate = parsedPredicate) === null || _parsedPredicate === void 0 ? void 0 : _parsedPredicate.pType} ${(_parsedPredicate2 = parsedPredicate) === null || _parsedPredicate2 === void 0 ? void 0 : _parsedPredicate2.pValue}`));
  };
  const CardBody = _ref3 => {
    var _overlay$presentation;
    let {
      overlay
    } = _ref3;
    return /*#__PURE__*/React.createElement(View, {
      style: styles.cardAttributes
    }, (_overlay$presentation = overlay.presentationFields) === null || _overlay$presentation === void 0 ? void 0 : _overlay$presentation.map(item => /*#__PURE__*/React.createElement(CardField, {
      item: item,
      key: item.name || item.toString()
    })));
  };
  const CardColor = _ref4 => {
    var _overlay$brandingOver;
    let {
      overlay
    } = _ref4;
    return /*#__PURE__*/React.createElement(View, {
      testID: testIdWithKey('CardColor'),
      style: [{
        backgroundColor: (_overlay$brandingOver = overlay.brandingOverlay) === null || _overlay$brandingOver === void 0 ? void 0 : _overlay$brandingOver.primaryBackgroundColor
      }, styles.cardColorContainer]
    });
  };
  const CardLogo = _ref5 => {
    var _overlay$brandingOver2, _overlay$brandingOver3, _ref6, _overlay$metaOverlay, _overlay$metaOverlay2;
    let {
      overlay
    } = _ref5;
    return /*#__PURE__*/React.createElement(View, {
      style: styles.logoContainer
    }, (_overlay$brandingOver2 = overlay.brandingOverlay) !== null && _overlay$brandingOver2 !== void 0 && _overlay$brandingOver2.logo ? /*#__PURE__*/React.createElement(Image, {
      source: toImageSource((_overlay$brandingOver3 = overlay.brandingOverlay) === null || _overlay$brandingOver3 === void 0 ? void 0 : _overlay$brandingOver3.logo),
      style: {
        resizeMode: 'cover',
        width: logoHeight,
        height: logoHeight,
        borderRadius: 8
      }
    }) : /*#__PURE__*/React.createElement(Text, {
      style: [TextTheme.normal, {
        fontSize: 0.5 * logoHeight,
        fontWeight: 'bold',
        alignSelf: 'center',
        color: ColorPallet.grayscale.black
      }]
    }, (_ref6 = ((_overlay$metaOverlay = overlay.metaOverlay) === null || _overlay$metaOverlay === void 0 ? void 0 : _overlay$metaOverlay.issuer) ?? ((_overlay$metaOverlay2 = overlay.metaOverlay) === null || _overlay$metaOverlay2 === void 0 ? void 0 : _overlay$metaOverlay2.name) ?? 'C') === null || _ref6 === void 0 ? void 0 : _ref6.charAt(0).toUpperCase()));
  };
  return overlay ? /*#__PURE__*/React.createElement(View, {
    style: styles.container
  }, /*#__PURE__*/React.createElement(View, {
    key: sharedData.identifiers.cred_def_id,
    style: styles.cardContainer
  }, /*#__PURE__*/React.createElement(CardColor, {
    overlay: overlay
  }), /*#__PURE__*/React.createElement(CardLogo, {
    overlay: overlay
  }), /*#__PURE__*/React.createElement(CardBody, {
    overlay: overlay
  }))) : null;
};
const SharedProofData = _ref7 => {
  let {
    recordId,
    onSharedProofDataLoad
  } = _ref7;
  const {
    agent
  } = useAgent();
  const {
    LoadingIndicator
  } = useAnimatedComponents();
  const styles = StyleSheet.create({
    container: {
      flexGrow: 1
    },
    loaderContainer: {
      height: 200,
      marginTop: 80
    }
  });
  if (!agent) {
    throw new Error('Unable to fetch agent from AFJ');
  }
  const [loading, setLoading] = useState(true);
  const [sharedData, setSharedData] = useState(undefined);
  useEffect(() => {
    getProofData(agent, recordId).then(data => {
      if (data) {
        const groupedSharedProofData = groupSharedProofDataByCredential(data);
        setSharedData(groupedSharedProofData);
        if (!onSharedProofDataLoad) return;
        onSharedProofDataLoad(Array.from(groupedSharedProofData.values()));
      }
    }).finally(() => {
      setLoading(false);
    });
  }, [recordId]);
  return /*#__PURE__*/React.createElement(View, {
    style: styles.container
  }, loading && /*#__PURE__*/React.createElement(View, {
    style: styles.loaderContainer
  }, /*#__PURE__*/React.createElement(LoadingIndicator, null)), !loading && (sharedData === null || sharedData === void 0 ? void 0 : sharedData.size) && Array.from(sharedData.values()).map(item => /*#__PURE__*/React.createElement(SharedDataCard, {
    sharedData: item,
    key: item.identifiers.cred_def_id
  })));
};
export default SharedProofData;
//# sourceMappingURL=SharedProofData.js.map