{-# LANGUAGE TypeApplications #-}


-- | Copyright  : Will Thompson and Iñaki García Etxebarria
-- License    : LGPL-2.1
-- Maintainer : Iñaki García Etxebarria
-- 
-- Represents a precise time, with seconds and microseconds.
-- 
-- Similar to the struct timeval returned by the @gettimeofday()@
-- UNIX system call.
-- 
-- GLib is attempting to unify around the use of 64-bit integers to
-- represent microsecond-precision time. As such, this type will be
-- removed from a future version of GLib. A consequence of using @glong@ for
-- @tv_sec@ is that on 32-bit systems @GTimeVal@ is subject to the year 2038
-- problem.

#if (MIN_VERSION_haskell_gi_overloading(1,0,0) && !defined(__HADDOCK_VERSION__))
#define ENABLE_OVERLOADING
#endif

module GI.GLib.Structs.TimeVal
    ( 

-- * Exported types
    TimeVal(..)                             ,
    newZeroTimeVal                          ,


 -- * Methods
-- | 
-- 
--  === __Click to display all available methods, including inherited ones__
-- ==== Methods
-- [add]("GI.GLib.Structs.TimeVal#g:method:add"), [toIso8601]("GI.GLib.Structs.TimeVal#g:method:toIso8601").
-- 
-- ==== Getters
-- /None/.
-- 
-- ==== Setters
-- /None/.

#if defined(ENABLE_OVERLOADING)
    ResolveTimeValMethod                    ,
#endif

-- ** add #method:add#

#if defined(ENABLE_OVERLOADING)
    TimeValAddMethodInfo                    ,
#endif
    timeValAdd                              ,


-- ** fromIso8601 #method:fromIso8601#

    timeValFromIso8601                      ,


-- ** toIso8601 #method:toIso8601#

#if defined(ENABLE_OVERLOADING)
    TimeValToIso8601MethodInfo              ,
#endif
    timeValToIso8601                        ,




 -- * Properties


-- ** tvSec #attr:tvSec#
-- | seconds

    getTimeValTvSec                         ,
    setTimeValTvSec                         ,
#if defined(ENABLE_OVERLOADING)
    timeVal_tvSec                           ,
#endif


-- ** tvUsec #attr:tvUsec#
-- | microseconds

    getTimeValTvUsec                        ,
    setTimeValTvUsec                        ,
#if defined(ENABLE_OVERLOADING)
    timeVal_tvUsec                          ,
#endif




    ) where

import Data.GI.Base.ShortPrelude
import qualified Data.GI.Base.ShortPrelude as SP
import qualified Data.GI.Base.Overloading as O
import qualified Prelude as P

import qualified Data.GI.Base.Attributes as GI.Attributes
import qualified Data.GI.Base.BasicTypes as B.Types
import qualified Data.GI.Base.ManagedPtr as B.ManagedPtr
import qualified Data.GI.Base.GArray as B.GArray
import qualified Data.GI.Base.GClosure as B.GClosure
import qualified Data.GI.Base.GError as B.GError
import qualified Data.GI.Base.GHashTable as B.GHT
import qualified Data.GI.Base.GVariant as B.GVariant
import qualified Data.GI.Base.GValue as B.GValue
import qualified Data.GI.Base.GParamSpec as B.GParamSpec
import qualified Data.GI.Base.CallStack as B.CallStack
import qualified Data.GI.Base.Properties as B.Properties
import qualified Data.GI.Base.Signals as B.Signals
import qualified Control.Monad.IO.Class as MIO
import qualified Data.Coerce as Coerce
import qualified Data.Text as T
import qualified Data.Kind as DK
import qualified Data.ByteString.Char8 as B
import qualified Data.Map as Map
import qualified Foreign.Ptr as FP
import qualified GHC.OverloadedLabels as OL
import qualified GHC.Records as R
import qualified Data.Word as DW
import qualified Data.Int as DI
import qualified System.Posix.Types as SPT
import qualified Foreign.C.Types as FCT

-- Workaround for https://gitlab.haskell.org/ghc/ghc/-/issues/23392
#if MIN_VERSION_base(4,18,0)

#else

#endif

-- | Memory-managed wrapper type.
newtype TimeVal = TimeVal (SP.ManagedPtr TimeVal)
    deriving (Eq)

instance SP.ManagedPtrNewtype TimeVal where
    toManagedPtr (TimeVal p) = p

instance BoxedPtr TimeVal where
    boxedPtrCopy = \p -> B.ManagedPtr.withManagedPtr p (copyBytes 16 >=> B.ManagedPtr.wrapPtr TimeVal)
    boxedPtrFree = \x -> SP.withManagedPtr x SP.freeMem
instance CallocPtr TimeVal where
    boxedPtrCalloc = callocBytes 16


-- | Construct a t'TimeVal' struct initialized to zero.
newZeroTimeVal :: MonadIO m => m TimeVal
newZeroTimeVal = liftIO $ boxedPtrCalloc >>= wrapPtr TimeVal

instance tag ~ 'AttrSet => Constructible TimeVal tag where
    new _ attrs = do
        o <- newZeroTimeVal
        GI.Attributes.set o attrs
        return o


-- | Get the value of the “@tv_sec@” field.
-- When <https://github.com/haskell-gi/haskell-gi/wiki/Overloading overloading> is enabled, this is equivalent to
-- 
-- @
-- 'Data.GI.Base.Attributes.get' timeVal #tvSec
-- @
getTimeValTvSec :: MonadIO m => TimeVal -> m FCT.CLong
getTimeValTvSec s = liftIO $ withManagedPtr s $ \ptr -> do
    val <- peek (ptr `plusPtr` 0) :: IO FCT.CLong
    return val

-- | Set the value of the “@tv_sec@” field.
-- When <https://github.com/haskell-gi/haskell-gi/wiki/Overloading overloading> is enabled, this is equivalent to
-- 
-- @
-- 'Data.GI.Base.Attributes.set' timeVal [ #tvSec 'Data.GI.Base.Attributes.:=' value ]
-- @
setTimeValTvSec :: MonadIO m => TimeVal -> FCT.CLong -> m ()
setTimeValTvSec s val = liftIO $ withManagedPtr s $ \ptr -> do
    poke (ptr `plusPtr` 0) (val :: FCT.CLong)

#if defined(ENABLE_OVERLOADING)
data TimeValTvSecFieldInfo
instance AttrInfo TimeValTvSecFieldInfo where
    type AttrBaseTypeConstraint TimeValTvSecFieldInfo = (~) TimeVal
    type AttrAllowedOps TimeValTvSecFieldInfo = '[ 'AttrSet, 'AttrGet]
    type AttrSetTypeConstraint TimeValTvSecFieldInfo = (~) FCT.CLong
    type AttrTransferTypeConstraint TimeValTvSecFieldInfo = (~)FCT.CLong
    type AttrTransferType TimeValTvSecFieldInfo = FCT.CLong
    type AttrGetType TimeValTvSecFieldInfo = FCT.CLong
    type AttrLabel TimeValTvSecFieldInfo = "tv_sec"
    type AttrOrigin TimeValTvSecFieldInfo = TimeVal
    attrGet = getTimeValTvSec
    attrSet = setTimeValTvSec
    attrConstruct = undefined
    attrClear = undefined
    attrTransfer _ v = do
        return v
    dbgAttrInfo = P.Just (O.ResolvedSymbolInfo {
        O.resolvedSymbolName = "GI.GLib.Structs.TimeVal.tvSec"
        , O.resolvedSymbolURL = "https://hackage.haskell.org/package/gi-glib-2.0.30/docs/GI-GLib-Structs-TimeVal.html#g:attr:tvSec"
        })

timeVal_tvSec :: AttrLabelProxy "tvSec"
timeVal_tvSec = AttrLabelProxy

#endif


-- | Get the value of the “@tv_usec@” field.
-- When <https://github.com/haskell-gi/haskell-gi/wiki/Overloading overloading> is enabled, this is equivalent to
-- 
-- @
-- 'Data.GI.Base.Attributes.get' timeVal #tvUsec
-- @
getTimeValTvUsec :: MonadIO m => TimeVal -> m FCT.CLong
getTimeValTvUsec s = liftIO $ withManagedPtr s $ \ptr -> do
    val <- peek (ptr `plusPtr` 8) :: IO FCT.CLong
    return val

-- | Set the value of the “@tv_usec@” field.
-- When <https://github.com/haskell-gi/haskell-gi/wiki/Overloading overloading> is enabled, this is equivalent to
-- 
-- @
-- 'Data.GI.Base.Attributes.set' timeVal [ #tvUsec 'Data.GI.Base.Attributes.:=' value ]
-- @
setTimeValTvUsec :: MonadIO m => TimeVal -> FCT.CLong -> m ()
setTimeValTvUsec s val = liftIO $ withManagedPtr s $ \ptr -> do
    poke (ptr `plusPtr` 8) (val :: FCT.CLong)

#if defined(ENABLE_OVERLOADING)
data TimeValTvUsecFieldInfo
instance AttrInfo TimeValTvUsecFieldInfo where
    type AttrBaseTypeConstraint TimeValTvUsecFieldInfo = (~) TimeVal
    type AttrAllowedOps TimeValTvUsecFieldInfo = '[ 'AttrSet, 'AttrGet]
    type AttrSetTypeConstraint TimeValTvUsecFieldInfo = (~) FCT.CLong
    type AttrTransferTypeConstraint TimeValTvUsecFieldInfo = (~)FCT.CLong
    type AttrTransferType TimeValTvUsecFieldInfo = FCT.CLong
    type AttrGetType TimeValTvUsecFieldInfo = FCT.CLong
    type AttrLabel TimeValTvUsecFieldInfo = "tv_usec"
    type AttrOrigin TimeValTvUsecFieldInfo = TimeVal
    attrGet = getTimeValTvUsec
    attrSet = setTimeValTvUsec
    attrConstruct = undefined
    attrClear = undefined
    attrTransfer _ v = do
        return v
    dbgAttrInfo = P.Just (O.ResolvedSymbolInfo {
        O.resolvedSymbolName = "GI.GLib.Structs.TimeVal.tvUsec"
        , O.resolvedSymbolURL = "https://hackage.haskell.org/package/gi-glib-2.0.30/docs/GI-GLib-Structs-TimeVal.html#g:attr:tvUsec"
        })

timeVal_tvUsec :: AttrLabelProxy "tvUsec"
timeVal_tvUsec = AttrLabelProxy

#endif



#if defined(ENABLE_OVERLOADING)
instance O.HasAttributeList TimeVal
type instance O.AttributeList TimeVal = TimeValAttributeList
type TimeValAttributeList = ('[ '("tvSec", TimeValTvSecFieldInfo), '("tvUsec", TimeValTvUsecFieldInfo)] :: [(Symbol, DK.Type)])
#endif

-- method TimeVal::add
-- method type : OrdinaryMethod
-- Args: [ Arg
--           { argCName = "time_"
--           , argType =
--               TInterface Name { namespace = "GLib" , name = "TimeVal" }
--           , argCType = Just "GTimeVal*"
--           , direction = DirectionIn
--           , mayBeNull = False
--           , argDoc =
--               Documentation
--                 { rawDocText = Just "a #GTimeVal" , sinceVersion = Nothing }
--           , argScope = ScopeTypeInvalid
--           , argClosure = -1
--           , argDestroy = -1
--           , argCallerAllocates = False
--           , argCallbackUserData = False
--           , transfer = TransferNothing
--           }
--       , Arg
--           { argCName = "microseconds"
--           , argType = TBasicType TLong
--           , argCType = Just "glong"
--           , direction = DirectionIn
--           , mayBeNull = False
--           , argDoc =
--               Documentation
--                 { rawDocText = Just "number of microseconds to add to @time"
--                 , sinceVersion = Nothing
--                 }
--           , argScope = ScopeTypeInvalid
--           , argClosure = -1
--           , argDestroy = -1
--           , argCallerAllocates = False
--           , argCallbackUserData = False
--           , transfer = TransferNothing
--           }
--       ]
-- Lengths: []
-- returnType: Nothing
-- throws : False
-- Skip return : False

foreign import ccall "g_time_val_add" g_time_val_add :: 
    Ptr TimeVal ->                          -- time_ : TInterface (Name {namespace = "GLib", name = "TimeVal"})
    FCT.CLong ->                            -- microseconds : TBasicType TLong
    IO ()

{-# DEPRECATED timeValAdd ["(Since version 2.62)","t'GI.GLib.Structs.TimeVal.TimeVal' is not year-2038-safe. Use @guint64@ for","   representing microseconds since the epoch, or use t'GI.GLib.Structs.DateTime.DateTime'."] #-}
-- | Adds the given number of microseconds to /@time_@/. /@microseconds@/ can
-- also be negative to decrease the value of /@time_@/.
timeValAdd ::
    (B.CallStack.HasCallStack, MonadIO m) =>
    TimeVal
    -- ^ /@time_@/: a t'GI.GLib.Structs.TimeVal.TimeVal'
    -> FCT.CLong
    -- ^ /@microseconds@/: number of microseconds to add to /@time@/
    -> m ()
timeValAdd time_ microseconds = liftIO $ do
    time_' <- unsafeManagedPtrGetPtr time_
    g_time_val_add time_' microseconds
    touchManagedPtr time_
    return ()

#if defined(ENABLE_OVERLOADING)
data TimeValAddMethodInfo
instance (signature ~ (FCT.CLong -> m ()), MonadIO m) => O.OverloadedMethod TimeValAddMethodInfo TimeVal signature where
    overloadedMethod = timeValAdd

instance O.OverloadedMethodInfo TimeValAddMethodInfo TimeVal where
    overloadedMethodInfo = P.Just (O.ResolvedSymbolInfo {
        O.resolvedSymbolName = "GI.GLib.Structs.TimeVal.timeValAdd",
        O.resolvedSymbolURL = "https://hackage.haskell.org/package/gi-glib-2.0.30/docs/GI-GLib-Structs-TimeVal.html#v:timeValAdd"
        })


#endif

-- method TimeVal::to_iso8601
-- method type : OrdinaryMethod
-- Args: [ Arg
--           { argCName = "time_"
--           , argType =
--               TInterface Name { namespace = "GLib" , name = "TimeVal" }
--           , argCType = Just "GTimeVal*"
--           , direction = DirectionIn
--           , mayBeNull = False
--           , argDoc =
--               Documentation
--                 { rawDocText = Just "a #GTimeVal" , sinceVersion = Nothing }
--           , argScope = ScopeTypeInvalid
--           , argClosure = -1
--           , argDestroy = -1
--           , argCallerAllocates = False
--           , argCallbackUserData = False
--           , transfer = TransferNothing
--           }
--       ]
-- Lengths: []
-- returnType: Just (TBasicType TUTF8)
-- throws : False
-- Skip return : False

foreign import ccall "g_time_val_to_iso8601" g_time_val_to_iso8601 :: 
    Ptr TimeVal ->                          -- time_ : TInterface (Name {namespace = "GLib", name = "TimeVal"})
    IO CString

{-# DEPRECATED timeValToIso8601 ["(Since version 2.62)","t'GI.GLib.Structs.TimeVal.TimeVal' is not year-2038-safe. Use","   g_date_time_format_iso8601(dt) instead."] #-}
-- | Converts /@time_@/ into an RFC 3339 encoded string, relative to the
-- Coordinated Universal Time (UTC). This is one of the many formats
-- allowed by ISO 8601.
-- 
-- ISO 8601 allows a large number of date\/time formats, with or without
-- punctuation and optional elements. The format returned by this function
-- is a complete date and time, with optional punctuation included, the
-- UTC time zone represented as \"Z\", and the /@tvUsec@/ part included if
-- and only if it is nonzero, i.e. either
-- \"YYYY-MM-DDTHH:MM:SSZ\" or \"YYYY-MM-DDTHH:MM:SS.fffffZ\".
-- 
-- This corresponds to the Internet date\/time format defined by
-- <https://www.ietf.org/rfc/rfc3339.txt RFC 3339>,
-- and to either of the two most-precise formats defined by
-- the W3C Note
-- <http://www.w3.org/TR/NOTE-datetime-19980827 Date and Time Formats>.
-- Both of these documents are profiles of ISO 8601.
-- 
-- Use 'GI.GLib.Structs.DateTime.dateTimeFormat' or @/g_strdup_printf()/@ if a different
-- variation of ISO 8601 format is required.
-- 
-- If /@time_@/ represents a date which is too large to fit into a @struct tm@,
-- 'P.Nothing' will be returned. This is platform dependent. Note also that since
-- @GTimeVal@ stores the number of seconds as a @glong@, on 32-bit systems it
-- is subject to the year 2038 problem. Accordingly, since GLib 2.62, this
-- function has been deprecated. Equivalent functionality is available using:
-- 
-- 	
-- >
-- >GDateTime *dt = g_date_time_new_from_unix_utc (time_val);
-- >iso8601_string = g_date_time_format_iso8601 (dt);
-- >g_date_time_unref (dt);
-- 
-- 
-- The return value of 'GI.GLib.Structs.TimeVal.timeValToIso8601' has been nullable since GLib
-- 2.54; before then, GLib would crash under the same conditions.
-- 
-- /Since: 2.12/
timeValToIso8601 ::
    (B.CallStack.HasCallStack, MonadIO m) =>
    TimeVal
    -- ^ /@time_@/: a t'GI.GLib.Structs.TimeVal.TimeVal'
    -> m (Maybe T.Text)
    -- ^ __Returns:__ a newly allocated string containing an ISO 8601 date,
    --    or 'P.Nothing' if /@time_@/ was too large
timeValToIso8601 time_ = liftIO $ do
    time_' <- unsafeManagedPtrGetPtr time_
    result <- g_time_val_to_iso8601 time_'
    maybeResult <- convertIfNonNull result $ \result' -> do
        result'' <- cstringToText result'
        freeMem result'
        return result''
    touchManagedPtr time_
    return maybeResult

#if defined(ENABLE_OVERLOADING)
data TimeValToIso8601MethodInfo
instance (signature ~ (m (Maybe T.Text)), MonadIO m) => O.OverloadedMethod TimeValToIso8601MethodInfo TimeVal signature where
    overloadedMethod = timeValToIso8601

instance O.OverloadedMethodInfo TimeValToIso8601MethodInfo TimeVal where
    overloadedMethodInfo = P.Just (O.ResolvedSymbolInfo {
        O.resolvedSymbolName = "GI.GLib.Structs.TimeVal.timeValToIso8601",
        O.resolvedSymbolURL = "https://hackage.haskell.org/package/gi-glib-2.0.30/docs/GI-GLib-Structs-TimeVal.html#v:timeValToIso8601"
        })


#endif

-- method TimeVal::from_iso8601
-- method type : MemberFunction
-- Args: [ Arg
--           { argCName = "iso_date"
--           , argType = TBasicType TUTF8
--           , argCType = Just "const gchar*"
--           , direction = DirectionIn
--           , mayBeNull = False
--           , argDoc =
--               Documentation
--                 { rawDocText = Just "an ISO 8601 encoded date string"
--                 , sinceVersion = Nothing
--                 }
--           , argScope = ScopeTypeInvalid
--           , argClosure = -1
--           , argDestroy = -1
--           , argCallerAllocates = False
--           , argCallbackUserData = False
--           , transfer = TransferNothing
--           }
--       , Arg
--           { argCName = "time_"
--           , argType =
--               TInterface Name { namespace = "GLib" , name = "TimeVal" }
--           , argCType = Just "GTimeVal*"
--           , direction = DirectionOut
--           , mayBeNull = False
--           , argDoc =
--               Documentation
--                 { rawDocText = Just "a #GTimeVal" , sinceVersion = Nothing }
--           , argScope = ScopeTypeInvalid
--           , argClosure = -1
--           , argDestroy = -1
--           , argCallerAllocates = True
--           , argCallbackUserData = False
--           , transfer = TransferNothing
--           }
--       ]
-- Lengths: []
-- returnType: Just (TBasicType TBoolean)
-- throws : False
-- Skip return : False

foreign import ccall "g_time_val_from_iso8601" g_time_val_from_iso8601 :: 
    CString ->                              -- iso_date : TBasicType TUTF8
    Ptr TimeVal ->                          -- time_ : TInterface (Name {namespace = "GLib", name = "TimeVal"})
    IO CInt

{-# DEPRECATED timeValFromIso8601 ["(Since version 2.62)","t'GI.GLib.Structs.TimeVal.TimeVal' is not year-2038-safe. Use","   'GI.GLib.Structs.DateTime.dateTimeNewFromIso8601' instead."] #-}
-- | Converts a string containing an ISO 8601 encoded date and time
-- to a t'GI.GLib.Structs.TimeVal.TimeVal' and puts it into /@time_@/.
-- 
-- /@isoDate@/ must include year, month, day, hours, minutes, and
-- seconds. It can optionally include fractions of a second and a time
-- zone indicator. (In the absence of any time zone indication, the
-- timestamp is assumed to be in local time.)
-- 
-- Any leading or trailing space in /@isoDate@/ is ignored.
-- 
-- This function was deprecated, along with t'GI.GLib.Structs.TimeVal.TimeVal' itself, in GLib 2.62.
-- Equivalent functionality is available using code like:
-- 
-- 	
-- >
-- >GDateTime *dt = g_date_time_new_from_iso8601 (iso8601_string, NULL);
-- >gint64 time_val = g_date_time_to_unix (dt);
-- >g_date_time_unref (dt);
-- 
-- 
-- /Since: 2.12/
timeValFromIso8601 ::
    (B.CallStack.HasCallStack, MonadIO m) =>
    T.Text
    -- ^ /@isoDate@/: an ISO 8601 encoded date string
    -> m ((Bool, TimeVal))
    -- ^ __Returns:__ 'P.True' if the conversion was successful.
timeValFromIso8601 isoDate = liftIO $ do
    isoDate' <- textToCString isoDate
    time_ <- SP.callocBytes 16 :: IO (Ptr TimeVal)
    result <- g_time_val_from_iso8601 isoDate' time_
    let result' = (/= 0) result
    time_' <- (wrapPtr TimeVal) time_
    freeMem isoDate'
    return (result', time_')

#if defined(ENABLE_OVERLOADING)
#endif

#if defined(ENABLE_OVERLOADING)
type family ResolveTimeValMethod (t :: Symbol) (o :: DK.Type) :: DK.Type where
    ResolveTimeValMethod "add" o = TimeValAddMethodInfo
    ResolveTimeValMethod "toIso8601" o = TimeValToIso8601MethodInfo
    ResolveTimeValMethod l o = O.MethodResolutionFailed l o

instance (info ~ ResolveTimeValMethod t TimeVal, O.OverloadedMethod info TimeVal p) => OL.IsLabel t (TimeVal -> p) where
#if MIN_VERSION_base(4,10,0)
    fromLabel = O.overloadedMethod @info
#else
    fromLabel _ = O.overloadedMethod @info
#endif

#if MIN_VERSION_base(4,13,0)
instance (info ~ ResolveTimeValMethod t TimeVal, O.OverloadedMethod info TimeVal p, R.HasField t TimeVal p) => R.HasField t TimeVal p where
    getField = O.overloadedMethod @info

#endif

instance (info ~ ResolveTimeValMethod t TimeVal, O.OverloadedMethodInfo info TimeVal) => OL.IsLabel t (O.MethodProxy info TimeVal) where
#if MIN_VERSION_base(4,10,0)
    fromLabel = O.MethodProxy
#else
    fromLabel _ = O.MethodProxy
#endif

#endif


