#|

scryfall API parser

WIP

This downloads the API data. We haven't even parsed that data
yet. It's hundreds of GB.

|#

(in-package #:cl-user)

(defpackage #:cl-deck-builder2.models.mtg
  (:use :cl))

(in-package #:cl-deck-builder2.models.mtg)

(defparameter *base-scryfall-api-uri* "https://api.scryfall.com/")

(defun scryfall-api-uri (path)
  (format nil "~a~a" *base-scryfall-api-uri* path))

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;

(defvar *scryfall-api-data* nil
  "A list of SCRYFALL-API-DATA objects.")

(defclass scryfall-api-data ()
  ((|content_encoding| :accessor scryfall-content-encoding :initarg :|content_encoding|)
   (|content_type|     :accessor scryfall-content-type     :initarg :|content_type|)
   (|description|      :accessor scryfall-description      :initarg :|description|)
   (|download_uri|     :accessor scryfall-download-uri     :initarg :|download_uri|)
   (|id|               :accessor scryfall-id               :initarg :|id|)
   (|name|             :accessor scryfall-name             :initarg :|name|)
   (|object|           :accessor scryfall-object           :initarg :|object|)
   (|size|             :accessor scryfall-size             :initarg :|size|)
   (|type|             :accessor scryfall-type             :initarg :|type|)
   (|updated_at|       :accessor scryfall-updated-at       :initarg :|updated_at|)
   (|uri|              :accessor scryfall-uri              :initarg :|uri|)))

(defun get-scryfall-data ()
  (let ((json (getf
               (jonathan:parse
                (flex:octets-to-string
                 (drakma:http-request (scryfall-api-uri "bulk-data"))))
               :|data|)))
    (mapcar (lambda (row)
              (apply #'make-instance 'scryfall-api-data row))
            json)))

(defun load-scryfall-data ()
  (setf *scryfall-api-data*
        (get-scryfall-data)))

(defun size-in-gb (size)
  (float (/ size (* 1024 1024 1024))))

(defun get-bulk-data-uris (path)
  (with-open-file (out path
                       :direction :output
                       :if-exists :supersede
                       :if-does-not-exist :create)
    (format out "~{~A~%~}"
            (mapcar #'scryfall-download-uri *scryfall-api-data*))))
