import { useProofRequestTemplates } from '@hyperledger/aries-bifold-verifier';
import axios from 'axios';
import { useConfiguration } from '../contexts/configuration';
const calculatePreviousYear = yearOffset => {
  const pastDate = new Date();
  pastDate.setFullYear(pastDate.getFullYear() + yearOffset);
  return parseInt(pastDate.toISOString().split('T')[0].replace(/-/g, ''));
};
export const applyTemplateMarkers = templates => {
  if (!templates) return templates;
  const markerActions = {
    now: () => Math.floor(new Date().getTime() / 1000).toString(),
    currentDate: offset => calculatePreviousYear(parseInt(offset)).toString()
  };
  let templateString = JSON.stringify(templates);
  // regex to find all markers in the template so we can replace them with computed values
  const markers = [...templateString.matchAll(/"@\{(\w+)(?:\((\S*)\))?\}"/gm)];
  markers.forEach(marker => {
    const markerValue = markerActions[marker[1]](marker[2]);
    templateString = templateString.replace(marker[0], markerValue);
  });
  return JSON.parse(templateString);
};
export const applyDevRestrictions = templates => {
  return templates.map(temp => {
    return {
      ...temp,
      payload: {
        ...temp.payload,
        data: temp.payload.data.map(data => {
          var _data$requestedAttrib, _data$requestedPredic;
          return {
            ...data,
            requestedAttributes: (_data$requestedAttrib = data.requestedAttributes) === null || _data$requestedAttrib === void 0 ? void 0 : _data$requestedAttrib.map(attr => {
              return {
                ...attr,
                restrictions: [...(attr.restrictions ?? []), ...(attr.devRestrictions ?? [])],
                devRestrictions: []
              };
            }),
            requestedPredicates: (_data$requestedPredic = data.requestedPredicates) === null || _data$requestedPredic === void 0 ? void 0 : _data$requestedPredic.map(pred => {
              return {
                ...pred,
                restrictions: [...(pred.restrictions ?? []), ...(pred.devRestrictions ?? [])],
                devRestrictions: []
              };
            })
          };
        })
      }
    };
  });
};
export const useRemoteProofBundleResolver = indexFileBaseUrl => {
  if (indexFileBaseUrl) {
    return new RemoteProofBundleResolver(indexFileBaseUrl);
  } else {
    return new DefaultProofBundleResolver();
  }
};
export class RemoteProofBundleResolver {
  constructor(indexFileBaseUrl) {
    this.remoteServer = axios.create({
      baseURL: indexFileBaseUrl
    });
  }
  async resolve(acceptDevRestrictions) {
    if (this.templateData) {
      let templateData = this.templateData;
      if (acceptDevRestrictions) {
        templateData = applyDevRestrictions(templateData);
      }
      return Promise.resolve(templateData);
    }
    return this.remoteServer.get('proof-templates.json').then(response => {
      try {
        let templateData = response.data;
        this.templateData = templateData;
        if (acceptDevRestrictions) {
          templateData = applyDevRestrictions(templateData);
        }
        return templateData;
      } catch (error) {
        return undefined;
      }
    });
  }
  async resolveById(templateId, acceptDevRestrictions) {
    if (!this.templateData) {
      var _await$this$resolve;
      return (_await$this$resolve = await this.resolve(acceptDevRestrictions)) === null || _await$this$resolve === void 0 ? void 0 : _await$this$resolve.find(template => template.id === templateId);
    } else {
      let templateData = this.templateData;
      if (acceptDevRestrictions) {
        templateData = applyDevRestrictions(templateData);
      }
      const template = templateData.find(template => template.id === templateId);
      return template;
    }
  }
}
export class DefaultProofBundleResolver {
  constructor() {
    const {
      proofRequestTemplates
    } = useConfiguration();
    this.proofRequestTemplates = proofRequestTemplates ?? useProofRequestTemplates;
  }
  async resolve(acceptDevRestrictions) {
    return Promise.resolve(this.proofRequestTemplates(acceptDevRestrictions));
  }
  async resolveById(templateId, acceptDevRestrictions) {
    return Promise.resolve(this.proofRequestTemplates(acceptDevRestrictions).find(template => template.id === templateId));
  }
}
//# sourceMappingURL=proofBundle.js.map