(in-package :json)

(defun parse-json (string)
  (read-json-object string 0))

(defun json-lookahead (string start)
  (let ((obj-start (position-if-not #'whitespace-char-p string :start start)))
    (if obj-start
        (values (aref string obj-start) obj-start)
      (values :eof nil))))

(defun read-json-object (string start)
  (let ((char (json-lookahead string start)))
    (if (or (eq char :eof)
            (char/= char #\{))
        (if (zerop start)
            ;; sometimes twitter will return an error string rather than an object
            string
          (error "Expected start of object { but found ~:[end of input~;~:*~A~]" char))
      (multiple-value-bind (char index)
          (json-lookahead string (1+ start))
        (cond ((eql char :eof)
               (error "Expected end of object but got to end of string"))
              ((char= char #\})
               ;; end of object with no content
               (values '() (1+ index)))
              (t
               (loop for (name-value-pair next) = (multiple-value-list (read-json-name-value-pair string index)) then (multiple-value-list (read-json-name-value-pair string next))
                     for (lookahead l-ind) = (multiple-value-list (json-lookahead string next))
                     collect name-value-pair into pairs
                     do (setq next (1+ l-ind))
                     until (char/= lookahead #\,)
                     finally (if (char= lookahead #\})
                                 (return-from read-json-object (values (cons :object pairs) next))
                               (error "Expected end of object } but found ~:[end of input~;~:*~A~]" lookahead)))))))))

(defun end-of-object-p (string start)
  (let ((lookahead (json-lookahead string start)))
    (if (eql lookahead :eof)
        (error "End of input checking for end of object")
      (char= lookahead #\}))))

(defun read-json-name-value-pair (string start)
  (if (end-of-object-p string start)
      nil
    (multiple-value-bind (name index)
        (read-json-string string start)
      (multiple-value-bind (lookahead index)
          (json-lookahead string index)
        (cond ((eql lookahead :eof)
               (error "Expected name/value separator : but reached end of string"))
              ((char/= lookahead #\:)
               (error "Expected name/value separator : but got ~C" lookahead))
              (t
               (multiple-value-bind (object end-index)
                   (read-json-value string (1+ index))
               (values (list name object) end-index))))))))

(defun read-json-value (string start)
  (multiple-value-bind (lookahead index) 
      (json-lookahead string start)
    (cond ((eql lookahead :eos)
           (error "Expected to read json value but reached end of string"))
          ((char= lookahead #\{)
           (read-json-object string index))
          ((char= lookahead #\")
           (read-json-string string index))
          ((char= lookahead #\[)
           (read-json-array string index))
          ((or (char= lookahead #\-)
               (digit-char-p lookahead))
           (read-json-number string index))
          ((member lookahead '(#\t #\f #\n) :test #'char=)
           (read-json-literal string index))
          (t (error "Unknown json entity starting with character ~C" lookahead)))))
      
(defun read-json-literal (string index)
  (let ((string-len (length string)))
    (multiple-value-bind (initial-letter ind)
        (json-lookahead string index)
      (cond ((and (char= initial-letter #\n)
                (> string-len (+ ind 4))
                (string= string "null" :start1 ind :end1 (+ ind 4)))
             (values :null (+ ind 4)))
          ((and (char= initial-letter #\t)
                (> string-len (+ ind 4))
                (string= string "true" :start1 ind :end1 (+ ind 4)))
           (values :true (+ ind 4)))
          ((and (char= initial-letter #\f)
                (> string-len (+ ind 4))
                (string= string "false" :start1 ind :end1 (+ ind 5)))
           (values :false (+ ind 5)))
          (t (error "Unknown JSON literal starting with ~C" initial-letter))))))

(defun read-json-string (string start)
  (multiple-value-bind (lookahead start) (json-lookahead string start)
    (cond ((eql lookahead :eof)
            (error "Expected start of string \" but reached end of string"))
          ((char/= lookahead #\")
           (error "Expected start of string \" but found ~A" lookahead))
          (t
           (let (end-of-string)
             (loop for eos = (position #\" string :test #'char= :start (1+ start)) then (position #\" string :test #'char= :start (1+ eos))
                   until (or (null eos) (char/= (aref string (1- eos)) #\\))
                   finally (setq end-of-string eos))
             (if (null end-of-string)
                 (error "Expected end of string \" but found reached end of input")
               (values (let* ((json-string-chars (loop for i from (1+ start) below end-of-string
                                                       for ch = (aref string i)
                                                       if (char= ch #\\)
                                                       collect (let ((next-char (aref string (1+ i))))
                                                                 (incf i)
                                                                 (case next-char
                                                                   ((#\" #\\ #\/) next-char)
                                                                   (#\b #\backspace)
                                                                   (#\f #\formfeed)
                                                                   (#\n #\newline)
                                                                   (#\r #\return)
                                                                   (#\t #\tab)
                                                                   (#\u (let* ((charcode-string (subseq string (1+ i) (+ i 5)))
                                                                               (char-code (parse-integer charcode-string :radix 16)))
                                                                          (incf i 4)
                                                                          (code-char char-code)))
                                                                   (t (error "Unknown extended character found: \\~C" next-char))))
                                                       else
                                                       collect ch))
                              (json-string (make-string (length json-string-chars) :element-type 'character)))
                         (loop for i from 0
                               for ch in json-string-chars
                               do (setf (aref json-string i) ch))
                         json-string)
                       (1+ end-of-string))))))))

(defun read-json-number (string start)
  (let ((orig-start start)
        (string-len (length string))
        frac exp)
    (when (char= (aref string start) #\-)
      (incf start))
    (when (and (>= (1+ start) string-len)
               (char= (aref string start) #\0)
               (not (char= (aref string (1+ start)) #\.)))
      (error "Number can only start with 0 if 1<n<-1"))
    (loop for i from start below string-len
          while (digit-char-p (aref string i))
          finally (setf start i))
    (when (and (< start string-len)
               (char= (aref string start) #\.))
      (incf start)
      (unless (and (< start string-len)
                   (digit-char-p (aref string start)))
        (error "Expected digit after decimal point but found ~C" (aref string start)))
      (loop for i from start below string-len
            while (digit-char-p (aref string i))
            finally (setf frac t
                          start i)))
    (when (and (< start string-len)
               (or (char= (aref string start) #\e)
                   (char= (aref string start) #\E)))
      (incf start)
      (when (and (< start string-len)
                 (or (char= (aref string start) #\-)
                     (char= (aref string start) #\+)))
        (incf start))
      (unless (and (< start string-len)
                   (digit-char-p (aref string start)))
        (error "Expecting exponent digits but found ~C" (aref string start)))
      (loop for i from start below string-len
            while (digit-char-p (aref string i))
            finally (setf exp t
                          start i)))
    (values
     (if (or frac exp)
         (parse-float string :start orig-start :end start) ; (format nil "~A~@[.~A~]~@[E~A~]" int frac (and exp (format nil "~@[~C~]~A" exp-sign exp))))
       (parse-integer string :start orig-start :end start))
     start)))

(defun read-json-array (string start)
  (if (char/= (json-lookahead string start) #\[)
      (error "Expected start of array [ but found ~C" (aref string start))
    (progn
      (incf start)
      (let ((lookahead (json-lookahead string start)))
        (if (char= lookahead #\])
            (values '() (1+ start))
          (loop for (value next) = (multiple-value-list (read-json-value string start)) then (multiple-value-list (read-json-value string next))
                for (lookahead l-ind) = (multiple-value-list (json-lookahead string next))
                collect value into array
                until (char/= lookahead #\,)
                do (setq next (1+ l-ind))
                finally (if (char= lookahead #\])
                            (return-from read-json-array (values (cons :array array) (1+ next)))
                          (error "Expected to find end of array ] but found ~C" lookahead))))))))

(defun json-object-p (x)
  (and (listp x) (eq (car x) :object)))

(defun json-array-p (x)
  (and (listp x) (eq (car x) :array)))

(defun get-json-attribute (object error-p &rest path-elts)
  (let ((value object))
    (loop for path-elt in path-elts
          do (cond ((stringp path-elt)
                    (if (json-object-p value)
                        (let ((attribute (assoc path-elt (cdr value) :test #'string=)))
                          (if attribute
                              (setq value (second attribute))
                            (if error-p
                                (error "Attribute ~A not found in JSON object ~A" path-elt value)
                              (setq value nil))))
                      (error "Trying to find attribute ~A of non-JSON-object" path-elt)))
                   ((integerp path-elt)
                    (if (json-array-p value)
                        (if (< -1 path-elt (length (cdr value)))
                            (setq value (nth path-elt (cdr value)))
                          (if error-p
                              (error "Trying to get index ~D of JSON array of length ~D" path-elt (length (cdr value)))
                            (setq value nil)))
                      (error "Trying to find array element ~D of non-JSON-array" path-elt)))
                   (t (error "Unknown JSON attribute designator ~S, expecting string or integer" path-elt))))
    value))