-- This file is part of the Wire Server implementation.
--
-- Copyright (C) 2022 Wire Swiss GmbH <opensource@wire.com>
--
-- This program is free software: you can redistribute it and/or modify it under
-- the terms of the GNU Affero General Public License as published by the Free
-- Software Foundation, either version 3 of the License, or (at your option) any
-- later version.
--
-- This program is distributed in the hope that it will be useful, but WITHOUT
-- ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
-- details.
--
-- You should have received a copy of the GNU Affero General Public License along
-- with this program. If not, see <https://www.gnu.org/licenses/>.

-- | Time type conversion
module Wire.Sem.FromUTC where

import Data.Time (UTCTime)
import Data.Time.Clock.POSIX (utcTimeToPOSIXSeconds)
import Imports
import qualified SAML2.WebSSO.Types as SAML
import Wire.API.MLS.Epoch (Epoch (..))

-- | The class is helpful in interpreters for the 'Now' effect. It makes it
-- possible to use the interpreters for any time type so long as it implements
-- this single-method class.
class FromUTC a where
  fromUTCTime :: UTCTime -> a

instance FromUTC UTCTime where
  fromUTCTime :: UTCTime -> UTCTime
fromUTCTime = UTCTime -> UTCTime
forall a. a -> a
id

instance FromUTC SAML.Time where
  fromUTCTime :: UTCTime -> Time
fromUTCTime = UTCTime -> Time
SAML.Time

instance FromUTC Epoch where
  fromUTCTime :: UTCTime -> Epoch
fromUTCTime = Word64 -> Epoch
Epoch (Word64 -> Epoch) -> (UTCTime -> Word64) -> UTCTime -> Epoch
forall b c a. (b -> c) -> (a -> b) -> a -> c
. POSIXTime -> Word64
forall b. Integral b => POSIXTime -> b
forall a b. (RealFrac a, Integral b) => a -> b
floor (POSIXTime -> Word64)
-> (UTCTime -> POSIXTime) -> UTCTime -> Word64
forall b c a. (b -> c) -> (a -> b) -> a -> c
. UTCTime -> POSIXTime
utcTimeToPOSIXSeconds