#lang racket

(require net/url
         json
         "mastodon.rkt"
         "twitter.rkt"
         "configuration.rkt"
         srfi/8)

(define character-generator (string-append feuforeve:website "/Floraverse/CharacterGenerator/Tweet"))
(define (pick-character)
  (read-json
    (get-pure-port
      (string->url character-generator))))

; Function to generate a character
; Each string defining the character should be less than 140 characters (twitter limit)
; The concatenation of strings should be less than 500 characters (mastodon limit)
; The function generates characters as long as the limits are not respected
; The function returns two values: a list of strings for twitter and a single string for mastodon
(define (generate-messages)
  (define chr (pick-character))
  (define tweets (list
                   (hash-ref chr 'identity)
                   (hash-ref chr 'birth)
                   (hash-ref chr 'motto)
                   (hash-ref chr 'traits)))
  (define toot (string-join tweets "\n"))
  (if (or (>= (string-length toot) 500)
          (member #t (map (lambda (x) (>= (string-length x) 140)) tweets)))
      (generate-messages)
      (values tweets toot)))

; Post a character
(receive
  (tweets toot) (generate-messages)
  ; Send to mastodon
  (send
    (new mastodon-client%
        [instance floraverse:mastodon-instance]
        [authorization-bearer floraverse:mastodon-authorization-bearer])
    new-status
    toot
    #:visibility "public")
  ; Send to twitter
  (define client (new twitter-client%
                  [consumer-key floraverse:twitter-consumer-key]
                  [consumer-secret floraverse:twitter-consumer-secret]
                  [access-key floraverse:twitter-access-token]
                  [access-secret floraverse:twitter-access-token-secret]))
  (foldl
    (lambda (message id-previous)
      (hash-ref
        (send
          client
          status-update
          message
          #:in-reply-to-id id-previous)
        'id_str))
    #f
    tweets))
