
module Package where

import           Control.Monad.Reader           ( runReader )
import           Parser
import           Schpin.SCAD
import           System.Directory               ( copyFile
                                                , createDirectory
                                                , createDirectoryIfMissing
                                                , getCurrentDirectory
                                                )
import           Schpin.Walker
import           Schpin.Walker.Pkg
import           Schpin.Walker.SCAD
import           Schpin.Walker.SRDF
import           Schpin.Walker.URDF

data ConfType = Default | Folded | Expanded deriving (Show, Eq);

kokePackageConfig :: String -> PackageConfig
kokePackageConfig cwd = PackageConfig { pkg_name = "schpin_koke"
                               , scad_dir = cwd ++ "/out/tmp/scad"
                               , pkg_dir  = cwd ++ "/out/pkg/schpin_koke"
                               , src_dir  = cwd ++ "/src/scad"
                               , urdf_subdir = "/src/"
                               , srdf_subdir = "/src/"
                               }


exportExtras :: (ConfType -> SimpleWalker) -> IO()
exportExtras w = do
    cwd <- getCurrentDirectory
    let conf = kokePackageConfig cwd
    let ew   = ewalker conf Default
    mapM_ (uncurry renderSCAD)
        $ [ (cwd ++ "/out/gen/skeleton/default.scad", getSCADVisualSkeleton ew)
          , ( cwd ++ "/out/gen/skeleton/default_col.scad"
            , getSCADCollisionSkeleton ew
            )
          , ( cwd ++ "/out/gen/skeleton/folded.scad"
            , getSCADVisualSkeleton (ewalker conf Folded)
            )
          , ( cwd ++ "/out/gen/skeleton/expanded.scad"
            , getSCADVisualSkeleton (ewalker conf Expanded)
            )
          ]

    generateBOM (ew) (conf)
    generatePrint (ew) (conf)

  where
    ewalker conf conf_type = runReader (extendWalker $ w conf_type) $ conf

exportPackage :: (ConfType -> SimpleWalker) -> IO ()
exportPackage w = do
    cwd <- getCurrentDirectory
    let conf = kokePackageConfig cwd
    let ew   = ewalker conf Default
    generateWalkerPackage (w Default) conf

    createDirectoryIfMissing False (pkg_dir conf ++ "/launch")
    copyFile "launch/robot_description.launch"
             (pkg_dir conf ++ "/launch/robot_description.launch")
    copyFile "launch/koke_gazebo.launch"
             (pkg_dir conf ++ "/launch/koke_gazebo.launch")

    createDirectoryIfMissing False (pkg_dir conf ++ "/worlds")
    copyFile "worlds/koke.world"      (pkg_dir conf ++ "/worlds/koke.world")

    copyFile "general/CMakeLists.txt" (pkg_dir conf ++ "/CMakeLists.txt")
    copyFile "general/package.xml"    (pkg_dir conf ++ "/package.xml")

  where
    ewalker conf conf_type = runReader (extendWalker $ w conf_type) $ conf

