#lang pollen/mode racket/base

;; Copyright (c) 2018 Joel Dueck.
;;
;; Licensed under the Apache License, Version 2.0 (the "License");
;; you may not use this file except in compliance with the License.
;; A copy of the License is included with this source code, in the
;; file "LICENSE.txt".
;; You may also obtain a copy of the License at
;;
;;       http://www.apache.org/licenses/LICENSE-2.0
;;
;; Unless required by applicable law or agreed to in writing, software
;; distributed under the License is distributed on an "AS IS" BASIS,
;; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
;; See the License for the specific language governing permissions and
;; limitations under the License.
;;
;; Author contact information:
;;   joel@jdueck.net
;;   https://joeldueck.com
;; -------------------------------------------------------------------------

(require racket/date
         racket/string
         racket/file
         racket/system
         "../dust.rkt")

(provide main)

(define (normalize str)
  (define alphanum-only
    (regexp-replace* #rx"[^A-Za-z0-9 ]" str ""))
  (string-normalize-spaces (string-downcase alphanum-only) #px"\\s+" "-"))

(define (make-filename basename)
  (build-path (current-directory) articles-folder (string-append basename ".poly.pm")))

(define (comment . strs)
  (format "◊; ~a" (apply string-append strs)))

(define date-string
  (parameterize [(date-display-format 'iso-8601)]
    (date->string (current-date))))

(define (make-template-contents title)
  ◊string-append{
 #lang pollen

 ◊comment{Copyright ◊(substring date-string 0 4) by ◊|default-authorname|. All Rights Reserved.}

 ◊"◊"(define-meta published "◊date-string")
 ◊"◊"(define-meta series "seriesname")

 ◊"◊"title{◊title}

 Write here!})

(define (main)
  (display "Enter title: ")
  (define title (read-line))
  (cond [(non-empty-string? title)
         (define post-file (make-filename (normalize title)))
         (define post-contents (make-template-contents title))
         (display-to-file post-contents post-file)
         (displayln (format "Saved to ~a" post-file))

         ; the + argument tells vim to place the cursor at the last line of the file.
         (system (format "mvim + ~a" post-file))]))