module Persistence.Frequency
  ( FrequencyField(..)
  ) where

import qualified Data.Text                        as T
import           Database.SQLite.Simple           (SQLData (SQLText))
import           Database.SQLite.Simple.FromField (FromField (fromField),
                                                   fieldData)
import           Database.SQLite.Simple.Ok        (Ok (Errors, Ok))
import           Database.SQLite.Simple.ToField   (ToField (toField))

import           Common.Model                     (Frequency)

newtype FrequencyField = FrequencyField Frequency

instance FromField FrequencyField where
  fromField field =
    case fieldData field of
      SQLText text -> Ok (FrequencyField (read (T.unpack text) :: Frequency))
      _            -> Errors [error "SQLText field required for frequency"]

instance ToField FrequencyField where
  toField (FrequencyField f) = SQLText . T.pack . show $ f