aboutsummaryrefslogtreecommitdiffhomepage
path: root/src/Utils/ScoresFile.hs
blob: f981a4afff14189a6edd3b8050ec3238bdb7ad23 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
module Utils.ScoresFile ( readScoresFile
                        , writeScoresFile) where

import Types.Scores
import Types.Classes
import Data.Classes
import Data.Time.Clock.POSIX (getPOSIXTime)
import Control.Applicative ((<$>))
import System.IO (readFile, writeFile)
import Data.List (sort)
import System.Directory (getDirectoryContents, getCurrentDirectory)
import System.FilePath (takeExtension)
import Control.Monad (liftM)
import Data.List.Split (splitOn)
import Data.Maybe (fromJust)
import System.FilePath ((</>))
-- import Control.Monad.SariulClocks
import Control.Monad.Trans (liftIO)

scoresToCSV :: ScoresList -> String
scoresToCSV = unlines . foldr step []
  where
    step (theClass, (Score x y)) theLines =
                          (show theClass ++ "," ++ show x ++ "," ++ show y) : theLines

-- TODO: back these up

-- no malformed CSV handling here yet!
-- this function currently doesn't work
scoresFromCSV     :: String -> ScoresList
scoresFromCSV csv = foldr step [] (lines csv)
  where
     step line scores = (theClass, Score (read scoreString) (read timeString)) : scores
      where
        classString:scoreString:timeString:[] = splitOn "," line
        theClass = fromJust $ lookupSariulClass ((read . (:[]) . head) classString) ((read . (:[]) . last) classString)

-- -- try to read from scores-XX.csv where XX is largest timestamp
-- readScoresFile :: SariulScoresMonad a => a (Maybe ScoresList)
-- readScoresFile = do
--     curDir <- liftIO getCurrentDirectory
--     let dataDir = curDir </> "data"
--     filenames <- liftM (reverse . sort . filter isCSV) $ liftIO $ getDirectoryContents dataDir
--     if null filenames
--        then return Nothing
--        else do
--         -- let scores = liftM scoresFromCSV $ liftIO $ readFile (dataDir </> head filenames)
--         scores <- liftIO $ scoresFromCSV <$> readFile (dataDir </> head filenames)
--         putScores scores
--         return $ Just scores
--   where isCSV path = takeExtension path == ".csv"

-- -- writes to score-XX.csv where XX is unix timestamp: a simple-minded logging
-- writeScoresFile :: SariulScoresMonad a => a ()
-- writeScoresFile = do
--     scores <- getScores
--     curDir <- liftIO getCurrentDirectory
--     let dataDir = curDir </> "data"
--     timestamp <- liftM round $ liftIO getPOSIXTime
--     let filename = dataDir </> ("scores-" ++ show timestamp ++ ".csv")
--     liftIO $ writeFile filename (scoresToCSV scores)

readScoresFile = undefined
writeScoresFile = undefined