import Text.Printf
import Graphics.Rendering.Cairo
import Cell1D

rs :: Double
rs = 20

drawCell :: Int -> Cell -> Render ()
drawCell n c = do
    let n' = fromIntegral n
        (r,g,b) = if c == F then (0,0,0) else (1,1,1)

    setSourceRGB r g b
    rectangle (n' * rs) 0 rs rs
    fill

drawBackground :: Int -> Render ()
drawBackground num = do
    setSourceRGB 1 1 1
    rectangle 0 0 (cnum * rs) rs
    fill
    where
    cnum = fromIntegral num

drawLat :: [Cell] -> Render ()
drawLat cs = do
    drawBackground $ length cs
    let cns = zip [0..length cs - 1] cs

    mapM_ (uncurry drawCell) cns

cellsToFile :: FilePath -> [Cell] -> IO ()
cellsToFile path cells = withImageSurface FormatRGB24 pnw pnh df
    where
    pnw = length cells * floor rs
    pnh = floor rs
    df srf = do
        renderWith srf $ drawLat cells
        surfaceWriteToPNG srf path

genPaths :: String -> Int -> [FilePath]
genPaths prefix n = map (printf "%s%.03d.png" prefix) [0..n-1]

latsToFiles :: String -> [[Cell]] -> IO ()
latsToFiles prefix lats = mapM_ (uncurry cellsToFile) $ zip paths lats
    where
    paths = genPaths prefix $ length lats

main = do
    lat0 <- exampleLat3
    let result = take 500 $ runCell1D rule184 lat0
    latsToFiles "myDraw" result
