module Helpers
  ( v2x
  , v2y
  , drawMap
  ) where

import Data.List
import Data.List.Split
import qualified Data.Map as M
import Linear.V2

v2x :: V2 a -> a
v2x (V2 x _) = x

v2y :: V2 a -> a
v2y (V2 _ y) = y

getBounds :: M.Map (V2 Int) Integer -> (Int, Int, Int, Int)
getBounds m = (getMinX, getMinY, getMaxX, getMaxY)
  where
    getMaxX = getFromMap maximum v2x
    getMaxY = getFromMap maximum v2y
    getMinX = getFromMap minimum v2x
    getMinY = getFromMap minimum v2y
    getFromMap f1 f2 = M.foldrWithKey (\k _ result -> f1 [f2 k, result]) 0 m

drawMap :: M.Map Integer Char -> M.Map (V2 Int) Integer -> String
drawMap dict m =
  intercalate "\n" $
  transpose $
  reverse $ map reverse $
  chunksOf
    (abs (abs y1 - abs y2) + 1)
    [ let c = M.findWithDefault (-99) (V2 x y) m
       in M.findWithDefault ' ' c dict
    | x <- [x1 .. x2]
    , y <- [y1 .. y2]
    ]
  where
    (x1, y1, x2, y2) = getBounds m

