{-# OPTIONS_GHC -fno-warn-orphans #-}

module Data.Bool.Instances
  () where

import ClassyPrelude

import qualified Data.Csv as Csv
import Data.CaseInsensitive (CI)
import qualified Data.CaseInsensitive as CI
import Data.CaseInsensitive.Instances ()

import qualified Data.Text as Text

import Control.Monad.Fail


instance Csv.ToField Bool where
  toField True = "t"
  toField False = "f"

instance Csv.FromField Bool where
  parseField f = do
    (CI.map Text.strip -> t :: CI Text) <- Csv.parseField f
    (True <$ guard (isTrue t)) <|> (False <$ guard (isFalse t)) <|> fail "Could not decode Bool"
    where
      isTrue = flip elem
        [ "yes", "y", "ja", "j", "wahr", "w", "true", "t", "1" ]
      isFalse = flip elem
        [ "no", "n", "nein", "falsch", "f", "false", "0" ]
