{-# LANGUAGE FlexibleContexts #-}
module Database  where

import Control.Monad.IO.Class
import Control.Monad.State.Strict
import Database.HDBC.Sqlite3 
import Database.HDBC
import Data.List.Split
import System.Environment.FindBin
import Paths_Villefort
  
type Query = String
type Path  = String
type Subject = String


getSubjects :: IO [Subject]
getSubjects = (\x-> (!! 0) <$> x) <$> makeQuery "select Subject from todo where state = 0 group by Subject"

--path =fmap (\x -> (x !! 0) ++ "Villefort.app/Contents/Resources/") $  (Data.List.Split.splitOn "Villefort.app") <$> getProgPath
--path :: IO Path
path =fmap (\x -> (x !! 0) ++ "Villefort/") $  (Data.List.Split.splitOn "Villefort/") <$> getProgPath
--path = getDataDir


getDb :: IO Connection  
getDb =  getDataFileName "data/todo.db" >>= connectSqlite3 

conv :: [[SqlValue]] -> [[String]]
conv dat = Prelude.map (\x -> Prelude.map (\y -> fromSql y :: String) x) dat

makeQuery :: Query -> IO [[String]]
makeQuery query =  getDb >>=  \conn  ->  quickQuery' conn query [] >>=
  \taskRaw -> disconnect conn >> return ( conv taskRaw)

  

execQuery :: Query -> [Int] -> IO ()
execQuery query params =  getDb >>= \conn ->  prepare conn query >>=
  \stmt ->  execute stmt ( map toSql params) >>  commit conn >> disconnect conn