module Graphics.LambdaCube.Loader.StbImage (loadImage) where

import Data.Bitmap
import Data.ByteString.Lazy hiding (putStrLn)
import Foreign.Ptr
import qualified Codec.Image.STB as STB
import qualified Data.ByteString as SB

import Graphics.LambdaCube.Image
import Graphics.LambdaCube.PixelFormat

loadImage :: ImageLoader
loadImage name buf = STB.decodeImage (SB.pack $ unpack buf) >>= \result -> case result of
    Left err  -> do
        putStrLn $ "StbImage loader " ++ err
        return Nothing
    Right img -> do
        let pf = case bitmapPixelSizeInBytes img of
                1 -> PF_L8
                2 -> PF_BYTE_LA
                3 -> PF_R8G8B8
                4 -> PF_R8G8B8A8
                _ -> PF_UNKNOWN
            (w,h) = bitmapSize img
        putStrLn $ "StbImage loader " ++ "\"" ++ name ++ "\" loaded"
        putStrLn $ "StbImage loader " ++ "resolution = " ++ show w ++ " x " ++ show h ++ ", " ++ show (bitmapPixelSizeInBytes img) ++ " bytes per pixel"
        imgData <- withBitmap img $ \_ _ _ ptr -> SB.packCStringLen (castPtr ptr,bitmapSizeInBytes img)
        return $ Just Image
          { imName       = name
          , imHeight     = w
          , imWidth      = h
          , imDepth      = 1
          , imNumMipmaps = 0 -- TODO
          , imFormat     = pf
          , imData       = imgData
          }