import Test.HUnit
import Debian.Dpkg.DB
import Debian.Dpkg.Enums
import Debian.Dpkg.PkgSpec
import Debian.Dpkg.Types
import Debian.Dpkg.DpkgVersion

import Foreign.C.String (peekCString)
import Foreign.Storable (peek)
import qualified Data.ByteString as BS
import Data.ByteString.Char8 (pack)

test1 = TestCase (do
	p <- pkgSpecParsePkg "testpkg"
	let want = fromIntegral $ c'pkginfo'want p
	let eflag = fromIntegral $ c'pkginfo'eflag p
	let status = fromIntegral $ c'pkginfo'status p
	let priority = fromIntegral $ c'pkginfo'priority p
	sec <- peekCString $ c'pkginfo'section p
	cv <- getConfigVersion p
	assertEqual "want" (fromEnum Want_install) want
	assertEqual "eflag" (fromEnum Eflag_ok) eflag
        assertEqual "status" (fromEnum Stat_installed) status
	assertEqual "priority" (fromEnum Pri_optional) priority
	assertEqual "section" "games" sec
	assertEqual "configversion" "0.1.2-3" cv
	)

test2 = TestCase (do
        pp <- pkgList
        let p = pp !! 2
	let want = fromIntegral $ c'pkginfo'want p
        set <- peek $ c'pkginfo'set p
        name <- peekCString $ c'pkgset'name set
	cv <- getConfigVersion p
        assertEqual "numpkgs" 4 (length pp)
        assertEqual "name" "testpkg2" name
        assertEqual "want" (fromEnum Want_deinstall) want
	assertEqual "configversion" "1.2.3-4" cv
        )

test3 = TestCase (do
        cvr <- parseVersion (pack "9:8.7.6-5")
        case cvr of
             Left msg -> assertString msg
             Right v  -> do
                 vr <- peekDpkgVersion v
                 assertEqual "epoch" 9 (vr_epoch vr)
                 assertEqual "version" (pack "8.7.6") (vr_version vr)
                 assertEqual "revision" (pack "5") (vr_revision vr)
        )

test4 = TestCase (do
        cvr <- parseVersion (BS.empty)
        case cvr of
             Left msg -> return ()
             Right v  -> assertString "unexpected success"
        )

test5 = TestCase (do
        cvr1 <- parseVersion (pack "9:8.7.6-5")
        cvr2 <- parseVersion (pack "1:2.3.4-5")
        case (cvr1,cvr2) of
             (Right x, Right y) -> assertEqual "comparison" True (cvr1 > cvr2)
             otherwise -> assertFailure"Failed to parse one of the versions"
        )

test6 = TestCase (do
        cvr1 <- parseVersion (pack "1~1")
        cvr2 <- parseVersion (pack "1")
        case (cvr1,cvr2) of
             (Right x, Right y) -> assertEqual "comparison" True (cvr1 < cvr2)
             otherwise -> assertFailure"Failed to parse one of the versions"
        )

tests = TestList [TestLabel "pkgSpecParsePkg" test1
                , TestLabel "pkgList" test2
                , TestLabel "parseVersion good" test3
                , TestLabel "parseVersion bad" test4
                , TestLabel "parseVersion Ord" test5
                , TestLabel "parseVersion Ord tilde" test6 ]

main = setDbDir "./testdb" >> msdbInit >> runTestTT tests
