module Main (main) where

import           Codec.Compression.BZip
import           Control.DeepSeq        (deepseq)
import qualified Data.ByteString.Lazy   as BSL
import           System.Directory       (doesFileExist)
import           System.FilePath        ((-<.>))
import           Test.Tasty
import           Test.Tasty.Golden
import           Test.Tasty.HUnit

testDecompress :: FilePath -> TestTree
testDecompress fp =
    goldenVsString ("Decompress " ++ fp) (fp -<.> ".ref") (decompress <$> BSL.readFile fp)

testCompress :: FilePath -> TestTree
testCompress fp = testCase ("Roundtrip " ++ fp) $ do
    contents <- BSL.readFile fp
    let actual = decompress (compress contents)
    actual @?= contents

testValgrind :: TestTree
testValgrind = testCase "Unpack valgrind" $ do
    contents <- BSL.readFile "valgrind-3.15.0.tar.bz2"
    let actual = decompress contents
    assertBool "Unpacks w/o error" (actual `deepseq` True)

testValgrindPack :: TestTree
testValgrindPack = testCase "Pack valgrind" $ do
    contents <- BSL.readFile "valgrind-3.15.0.tar"
    let actual = compress contents
    assertBool "Packs w/o error" (actual `deepseq` True)

main :: IO ()
main = do
    valgrind <- (&&) <$> doesFileExist "valgrind-3.15.0.tar.bz2" <*> doesFileExist "valgrind-3.15.0.tar"
    let go =
            if valgrind
                then (testValgrind:) . (testValgrindPack:)
                else id

    defaultMain $
        testGroup "bz2" (go [testDecompression, testCompression])

    where
        testDecompression = testGroup "Decompress"
            [ testDecompress "test/data/sample1.bz2"
            , testDecompress "test/data/sample2.bz2"
            , testDecompress "test/data/sample3.bz2"
            ]
        testCompression = testGroup "Compress"
            [ testCompress "test/data/sample1.ref"
            , testCompress "test/data/sample2.ref"
            , testCompress "test/data/sample3.ref"
            ]
