module Persistence ( saveLastRead, loadLastRead, ) where import Control.Exception (SomeException, try) import qualified Data.Text as T import qualified Data.Text.IO as TIO import System.Directory (XdgDirectory (XdgData), createDirectoryIfMissing, getXdgDirectory) import System.FilePath (()) import Text.Read (readMaybe) import Types (ChapterIndex(..)) saveLastRead :: FilePath -> ChapterIndex -> IO () saveLastRead bPath (ChapterIndex chapterIdx) = do dataDir <- getXdgDirectory XdgData "svitak" createDirectoryIfMissing True dataDir let configFile = dataDir "last_read.txt" let content = T.pack bPath <> T.pack "\n" <> T.pack (show chapterIdx) TIO.writeFile configFile content putStrLn $ "Progress saved to: " ++ configFile loadLastRead :: IO (Maybe (FilePath, ChapterIndex)) loadLastRead = do dataDir <- getXdgDirectory XdgData "svitak" let configFile = dataDir "last_read.txt" result <- try (TIO.readFile configFile) :: IO (Either SomeException T.Text) case result of Left _ -> pure Nothing Right content -> do let linesOfFile = T.lines content case linesOfFile of [path, idxStr] | Just idx <- readMaybe (T.unpack idxStr) -> pure $ Just (T.unpack path, ChapterIndex idx) _ -> pure Nothing