{-# LANGUAGE OverloadedStrings #-}

module Main (main) where

import Data.ByteString (ByteString)
import Data.Text (pack)
import Kafka.Producer
import Control.Concurrent
import Text.JSON
import Messages
import Control.Monad
import System.Environment
import System.IO

-- We only launch a single RedPanda broker to save resources
broker = BrokerAddress "redpanda:9092"

--producerProps :: ProducerProperties
--producerProps = brokersList [broker]

producerProps :: IO ProducerProperties
producerProps = do
    threadDelay 1000000
    broker <- getEnv "BOOTSTRAP_BROKERS"
    print $ "using kafka brokers: " <> broker
    return $ brokersList $ pure $ BrokerAddress $ pack $ broker

firstTopic = TopicName "great.ideas"
secondTopic = TopicName "stand.back"
thirdTopic = TopicName "oh.no"
credsTopic = TopicName "credentials"

producer :: IO KafkaProducer
producer = do
    props <- producerProps
    prod <- newProducer props
    case prod of
        Left e -> print e >>
            print "Failed to create kafka producer, retrying in 5 seconds" >>
            threadDelay 5000000 >>
            producer
        Right p -> return p

mkMessage :: ByteString -> TopicName -> ProducerRecord
mkMessage v topic = ProducerRecord
                  { prTopic = topic
                  , prPartition = UnassignedPartition
                  , prKey = Nothing
                  , prValue = Just v
                  }

produce :: KafkaProducer -> TopicName -> ByteString -> IO ()
produce p topic msg =
    produceMessage p (mkMessage msg topic) >>= mapM_ print

challenge1Prod :: KafkaProducer -> IO ()
challenge1Prod p =
    challenge1Msg >>= produce p firstTopic

challenge2Prod :: KafkaProducer -> IO ()
challenge2Prod p =
    produce p secondTopic challenge2Msg

challenge3Prod :: KafkaProducer -> IO ()
challenge3Prod p =
    challenge3Msg >>= produce p thirdTopic

-- Push the flags where needed
initChallenge :: KafkaProducer -> IO ()
initChallenge p = do
    print "Initializing challenge"
    produce p secondTopic challenge2FlagMsg
    produce p credsTopic challenge3FlagMsg

main :: IO ()
main = do
    hSetBuffering stdout LineBuffering
    p <- producer
    initChallenge p
    forever $ do
        print "Pushing to kafka"
        challenge1Prod p
        challenge2Prod p
        challenge3Prod p
        flushProducer p
        threadDelay 10000000
