import "registry-service.aqua"
import PeerId, Peer, Sig, SignResult from "@fluencelabs/aqua-lib/builtin.aqua"
import "@fluencelabs/trust-graph/trust-graph.aqua"

func getKeySignature(label: string, timestamp_created: u64) -> SignResult:
  bytes <- Registry.get_key_bytes(label, nil, timestamp_created, nil, "")
  on INIT_PEER_ID via HOST_PEER_ID:
    result <- Sig.sign(bytes)
  <- result

func getRecordMetadata(key_id: string, value: string, peer_id: string, relay_id: []string, service_id: []string, solution: []u8) -> ?RecordMetadata, ?string:
  t <- Peer.timestamp_sec()
  bytes <- Registry.get_record_metadata_bytes(key_id, INIT_PEER_ID, t, value, peer_id, relay_id, service_id, solution)

  on INIT_PEER_ID via HOST_PEER_ID:
    sig_result <- Sig.sign(bytes)

  result: ?RecordMetadata
  error: *string
  if sig_result.success == true:
    result <- Registry.create_record_metadata(key_id, INIT_PEER_ID, t, value, peer_id, relay_id, service_id, solution, sig_result.signature!)
  else:
    error <<- sig_result.error!

  <- result, error

func getRecordSignature(metadata: RecordMetadata, timestamp_created: u64) -> SignResult:
  signature: *SignResult

  if metadata.peer_id != INIT_PEER_ID:
    on metadata.peer_id via HOST_PEER_ID:
      bytes <- Registry.get_record_bytes(metadata, timestamp_created)
      signature <- Sig.sign(bytes)
  else:
    on HOST_PEER_ID:
      bytess <- Registry.get_record_bytes(metadata, timestamp_created)
      on INIT_PEER_ID:
        signature <- Sig.sign(bytess)

  <- signature!

func getTombstoneSignature(key_id: string, peer_id: string, timestamp_issued: u64, solution: []u8) -> SignResult:
  bytes <- Registry.get_tombstone_bytes(key_id, INIT_PEER_ID, peer_id, timestamp_issued, solution)
  on INIT_PEER_ID via HOST_PEER_ID:
    result <- Sig.sign(bytes)
  <- result

func registerKey(label: string, timestamp_created: u64, signature: []u8) -> RegisterKeyResult:
  t <- Peer.timestamp_sec()
  weight <- TrustGraph.get_weight(%init_peer_id%, t)
  result <- Registry.register_key(label, nil, timestamp_created, nil, "", signature, weight, t)
  <- result

func putRecord(metadata: RecordMetadata, timestamp_created: u64, signature: []u8) -> RegistryResult:
  t <- Peer.timestamp_sec()
  weight <- TrustGraph.get_weight(metadata.issued_by, t)
  result <- Registry.put_record(metadata, timestamp_created, signature, weight, t)
  <- result

func addTombstone(key_id: string, peer_id: string, timestamp_issued: u64, solution: []u8, signature: []u8) -> RegistryResult:
   t <- Peer.timestamp_sec()
  result <- Registry.add_tombstone(key_id, INIT_PEER_ID, peer_id, timestamp_issued, solution, signature, t)
  <- result

func getKeyMetadata(key_id: string) -> GetKeyMetadataResult:
  result <- Registry.get_key_metadata(key_id)
  <- result

func republishKey(key: Key) -> RegistryResult:
  t <- Peer.timestamp_sec()
  weight <- TrustGraph.get_weight(key.owner_peer_id, t)
  result <- Registry.republish_key(key, weight, t)
  <- result
