; Author: Yasir M. Arsanukaev <yarsanukaev AT gmail DOT com>
; License: The 2-clause BSD license. See the file LICENSE.

#lang racket

(require racket/serialize)

(require bert)

(require "errors.ss")

(provide encode-scheme-request

(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)))
      ((equal? resp-kind 'reply)
       (vect-get-elem 1))
      ((equal? resp-kind 'noreply)
      ((equal? resp-kind 'error)
       (error-rpc (vect-get-elem 1)))
       (bertrpc-error "Invalid response received from server.")))))