#!/usr/bin/rlwrap /usr/bin/runhaskell

import System.IO
import System.Environment
import Network.Curl.Easy
import Database.HDBC
import Database.HDBC.PostgreSQL (connectPostgreSQL)

import qualified Embeddings as E

-- =====================

embed :: Statement -> Statement -> [Int] -> IO ()
embed sQ uQ idArray = do
 mapM_ (singleEmbed) idArray
  where
   singleEmbed :: Int -> IO ()
   singleEmbed id = do
    execute sQ [toSql id]
    result <- fetchAllRows sQ
    putStrLn $ show id 
    let sym = (fromSql((result!!0)!!0) :: String)
    --putStrLn sym
    let chap = takeWhile (/=' ') (fromSql((result!!0)!!1) :: String)
    --putStrLn chap
    let gender = (fromSql((result!!0)!!2) :: String)
    --putStrLn gender
    let gondar = if gender=="f" then "female" else if gender=="m" then "male" else "either male or female"
    --putStrLn gondar
    let restQuery = "search_document: chapter: " ++ chap ++ ". gender: " ++ gondar ++ ". symptom: " ++ sym ++ "."
    --putStrLn restQuery

    resp <- E.doQuery restQuery -- runs the REST request and returns a Response
    --print resp
    --putStrLn "The returned text is:"
    let emb = (E.getEmbedding resp)
    --putStrLn emb
    execute uQ [toSql (emb::String), toSql (id::Int)] -- the type casts are necessary
    return ()


-- ====================

main = do
 args <- getArgs
 let numArgs = read (args!!0) :: Int -- how many tuples to update

 c <- connectPostgreSQL "host=localhost port=5433 dbname=homoeopim user=homoeopim password=<database_password>"
 let queryString = "select id from symptom_embedding where embedding is null order by id limit ?"
 targetList <- prepare c queryString
 execute targetList [toSql (show numArgs)] -- only that many tuples
 result <- fetchAllRows targetList
 let res = map (!!0) result
 let res1 = map (fromSql) res :: [Int]
 --print res1
 
 let symptomQuery = "select symptom, chapter, gender from symptom where id = ?"
 sQ <- prepare c symptomQuery

 let updateQuery = "update symptom_embedding set embedding = ? where id = ?"
 uQ <- prepare c updateQuery

 curl_global_init 0
 
 embed sQ uQ res1
 commit c
 disconnect c
 --resp <- doQuery input -- runs the REST request and returns a Response
 --print resp
 --putStrLn "The returned text is:"
 --putStrLn (getEmbedding resp) -- takes a Response and returns String
 curl_global_cleanup -- necessary -- frees and cleans up
