{-# LANGUAGE ScopedTypeVariables #-}

-- 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/>.

-- | wai-route-0.4.0 uses a 'Tree' type for route construction.  This module lets you
-- construct the simpler metrics routing tree from that.
module Data.Metrics.WaiRoute where

import Data.Metrics.Types
import Imports
import Network.Wai.Route.Tree as Tree

treeToPaths :: (HasCallStack) => Tree a -> Paths
treeToPaths :: forall a. HasCallStack => Tree a -> Paths
treeToPaths = ([Char] -> Paths)
-> (Paths -> Paths) -> Either [Char] Paths -> Paths
forall a c b. (a -> c) -> (b -> c) -> Either a b -> c
either [Char] -> Paths
forall a. HasCallStack => [Char] -> a
error Paths -> Paths
forall a. a -> a
id (Either [Char] Paths -> Paths)
-> (Tree a -> Either [Char] Paths) -> Tree a -> Paths
forall b c a. (b -> c) -> (a -> b) -> a -> c
. [[ByteString]] -> Either [Char] Paths
mkTree ([[ByteString]] -> Either [Char] Paths)
-> (Tree a -> [[ByteString]]) -> Tree a -> Either [Char] Paths
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (Payload a -> [ByteString]) -> [Payload a] -> [[ByteString]]
forall a b. (a -> b) -> [a] -> [b]
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
fmap (ByteString -> [ByteString]
Tree.segments (ByteString -> [ByteString])
-> (Payload a -> ByteString) -> Payload a -> [ByteString]
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Payload a -> ByteString
forall a. Payload a -> ByteString
path) ([Payload a] -> [[ByteString]])
-> (Tree a -> [Payload a]) -> Tree a -> [[ByteString]]
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Tree a -> [Payload a]
forall a. Tree a -> [Payload a]
Tree.toList