encodes.rkt
; Author: Yasir M. Arsanukaev <yarsanukaev AT gmail DOT com>
; License: The 2-clause BSD license. See LICENSE for details.

#lang racket

(require racket/serialize)

(require (prefix-in bert: (planet yasir/racket-bert:1)))

(require "errors.ss")

(provide encode-scheme-request
         decode-bert-response)

(define (error-rpc err)
  (let ((level (vector-ref err 0))
        (code (vector-ref err 1))
        (klass (vector-ref err 2))
        (message (vector-ref err 3))
        (backtrace (vector-ref err 4)))
    (bertrpc-raise-exn level (cons code message) klass backtrace)))

(define (encode-scheme-request scheme-request)
  (bert:encode scheme-request))

(define (decode-bert-response bert-response)
  (let* ((scheme-response (bert:decode bert-response))
         (vect-get-elem (lambda (n) (vector-ref scheme-response n)))
         (resp-kind (vect-get-elem 0)))
    (cond 
      ((equal? resp-kind 'reply)
       (vect-get-elem 1))
      ((equal? resp-kind 'noreply)
       'nil)
      ((equal? resp-kind 'error)
       (error-rpc (vect-get-elem 1)))
      (else
       (bertrpc-error "Invalid response received from server.")))))