;; (load "util.cl")

;; -------------------
;; cURL HTTP interface
;; -------------------

(defun response-version (response)
  (cdr (assoc 'response-version response)))

(defun response-status (response)
  (cdr (assoc 'response-status response)))

(defun response-reason-phrase (response)
  (cdr (assoc 'response-phrase response)))

(defun response-headers (response)
  (cdr (assoc 'response-headers response)))

(defun response-headers-value (response key)
  (assoc key (cdr (assoc 'response-headers response))))

(defun response-file-path (response)
  (cdr (assoc 'response-file response)))

(defun response-file-as-string (response)
  (file-lines (cdr (assoc 'response-file response))))

(defun http-request (&key url 
			  (port 80) 
			  (method 'get) 
			  (request-header nil) 
			  (response-header-only nil)
			  (variables nil))
  (let ((response-header-file (make-temporary-filename "Temp/curl/"))
	(response-body-file (make-temporary-filename "Temp/curl/"))
	(curl-command nil)
	(response nil))
    
    ;; build the command
    ;; for now only GET and POST are implemented
    (cond 
     ((string-equal method 'get)
      (if variables
	  (setf curl-command 
		(format nil 
			"curl -s \"~a?~a\" -D ~a" 
			url 
			(construct-curl-variable-argument variables)
			response-header-file))
	(setf curl-command 
	      (format nil "curl -s \"~a\" -D ~a" 
                          url response-header-file))))
     ((string-equal method 'post)
      (if variables
	  (setf curl-command 
		(format nil 
			"curl -d \"~a\" -s \"~a\" -D ~a" 
			(construct-curl-variable-argument variables)
			url 
			response-header-file))
	(error "POST requires data (variables)!")))
     (t (error "Unknown method: ~a!" method)))
    
    ;; identify directory
    (setf curl-command (concatenate 'string "C:\\Progra~1\\Curl\\curl-7.21.7\\" curl-command))
    (princ curl-command)(terpri)

    ;; do we want the body of the response?
    (if response-header-only
	(setf curl-command (concatenate 'string curl-command " -I"))
      (setf curl-command (concatenate 'string 
				      curl-command 
				      (format nil 
					      " -o ~a" 
					      response-body-file))))
    
    ;; add the custom headers
    (setf curl-command 
	  (concatenate 'string
		       curl-command
		       (construct-curl-header-arguments request-header)))
    
    
    ;; finally supress every trace of output to stdout
    (setf curl-command (concatenate 'string
				    curl-command
				    " >/dev/null 2>&1"))
    
    ;; make the request!
    ;;(princ curl-command) (terpri)
    (run-shell-command curl-command :wait t)
    
    ;; parse the response-header
    (setf response (parse-response response-header-file 
				   (unless response-header-only
				     response-body-file)))
    
    ;; we don't need the header any more
    (delete-file response-header-file)
    
    response))
