package com.rdkr.tide_display.backend.crypto.platforms;

import com.rdkr.tide_display.backend.crypto.Platforms;
import java.io.FileReader;
import java.security.PrivateKey;
import lombok.val;
import org.bouncycastle.asn1.pkcs.PrivateKeyInfo;
import org.bouncycastle.openssl.PEMParser;
import org.bouncycastle.openssl.jcajce.JcaPEMKeyConverter;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Component;
import org.springframework.util.ResourceUtils;

@Component("AppleCrypto")
public class AppleCrypto implements Platforms {

  @Cacheable(value = "privateKey", key = "#filename")
  public PrivateKey loadPrivateKey(String filename) {
    try {
      val file = ResourceUtils.getFile("classpath:apple/" + filename );
      val pemParser = new PEMParser(new FileReader(file));
      val converter = new JcaPEMKeyConverter();
      val object = (PrivateKeyInfo) pemParser.readObject();
      val pKey = converter.getPrivateKey(object);
      pemParser.close();
      return pKey;
    } catch (Exception e) {
      throw new RuntimeException("Failed to load private key", e);
    }
  }
}
