package com.rdkr.tide_display.backend.apple.snapshot;

import com.rdkr.tide_display.backend.apple.Snapshot;
import com.rdkr.tide_display.backend.crypto.Platforms;
import java.net.URI;
import java.nio.charset.StandardCharsets;
import java.security.Signature;
import java.util.Base64;
import lombok.val;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.util.UriComponentsBuilder;

@Component()
public class SnapshotImpl implements Snapshot {

  private final Platforms platforms;

  @Value("${APPLE_TEAM_ID:dummy}")
  private String teamId;

  @Value("${APPLE_KEY_ID:dummy}")
  private String keyId;

  public SnapshotImpl(@Qualifier("AppleCrypto") Platforms platforms) {
    this.platforms = platforms;
  }

  public URI generateSnapshotURI(double latitude, double longitude) {
    val uriBuilder = UriComponentsBuilder.fromUriString("https://snapshot.apple-mapkit.com/api/v1/snapshot")
        .queryParam("center", latitude + "," + longitude)
        .queryParam("t", "standard")
        .queryParam("scale", "1")
        .queryParam("size", "540x540")
        .queryParam("lang", "de-DE")
        .queryParam("poi", "0")
        .queryParam("teamId", teamId)
        .queryParam("keyId", keyId);
    return signRequest(uriBuilder);
  }

  private URI signRequest(UriComponentsBuilder uriBuilder) {
    try {
      val pk = platforms.loadPrivateKey("MapKit_D28AJ2A3UT.p8");
      val signature = Signature.getInstance("SHA256withECDSA", "BC");
      signature.initSign(pk);
      signature.update(uriBuilder.toString().getBytes());
      val signatureBytes = new String(signature.sign(), StandardCharsets.UTF_8);
      val sign = Base64.getEncoder().encodeToString(signatureBytes.getBytes());
      return uriBuilder
          .queryParam("signature", sign)
          .build()
          .toUri();
    } catch (Exception e) {
      throw new RuntimeException(e);
    }
  }

}
