-- | Core functions for parsing a png file
module MetaJuicer.PNG.PNGJuicer 
where

import qualified Data.ByteString.Lazy as Byte
import qualified Data.ByteString.Lazy.Char8 as Char8
import qualified Data.ByteString as ByteS
import qualified Data.ByteString.Char8 as Char8S
import MetaJuicer.MetaJuicer
import MetaJuicer.PNG.Chunk
import MetaJuicer.ByteHelper
import Data.Attoparsec.Lazy as Atto
import Debug.Trace

-- | Begins parsing the file
getPNG :: Parser Juice 
getPNG = (string $ ByteS.pack [137,80,78,71,13,10,26,10]) >> parseChunks >>= \ x -> return $ JuiceT ("PNG File",x)

-- | splits up the file into chunks and runs extractJuice on them
parseChunks :: Parser Juice
parseChunks = do retVal <- many1 getChunk <?> "failure while parsing chunks"
                 return $ JuiceL retVal

-- | Parses single chunk 
getChunk :: Parser Juice
getChunk = do len <- byteToInt `fmap` Atto.take 4 <?> "Failed to get chunk length"
              ctype <- Char8S.unpack `fmap` Atto.take 4 <?> "Failed to get chunk type"
              juice <- parseData len ctype <?> "Failed to parse chunk data"
              Atto.take 4
              return juice
