module Iri.Data.Functions where

import Iri.Data.Types
import Iri.Prelude

-- | Try to specialize a general IRI to HTTP
httpIriFromIri :: Iri -> Either Text HttpIri
httpIriFromIri :: Iri -> Either Text HttpIri
httpIriFromIri (Iri (Scheme ByteString
scheme) Hierarchy
hierarchy Query
query Fragment
fragment) =
  do
    Security
security <- case ByteString
scheme of
      ByteString
"http" -> Security -> Either Text Security
forall a b. b -> Either a b
Right (Bool -> Security
Security Bool
False)
      ByteString
"https" -> Security -> Either Text Security
forall a b. b -> Either a b
Right (Bool -> Security
Security Bool
True)
      ByteString
_ -> Text -> Either Text Security
forall a b. a -> Either a b
Left (Text
"Not an HTTP scheme: " Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> (String -> Text
forall a. IsString a => String -> a
fromString (String -> Text) -> (ByteString -> String) -> ByteString -> Text
forall b c a. (b -> c) -> (a -> b) -> a -> c
forall {k} (cat :: k -> k -> *) (b :: k) (c :: k) (a :: k).
Category cat =>
cat b c -> cat a b -> cat a c
. ByteString -> String
forall a. Show a => a -> String
show) ByteString
scheme)
    case Hierarchy
hierarchy of
      AuthorisedHierarchy (Authority UserInfo
userInfo Host
host Port
port) Path
path -> case UserInfo
userInfo of
        UserInfo
MissingUserInfo -> HttpIri -> Either Text HttpIri
forall a b. b -> Either a b
Right (Security -> Host -> Port -> Path -> Query -> Fragment -> HttpIri
HttpIri Security
security Host
host Port
port Path
path Query
query Fragment
fragment)
        PresentUserInfo (User ByteString
_) Password
_ -> Text -> Either Text HttpIri
forall a b. a -> Either a b
Left (Text
"User Info is present")
      Hierarchy
_ -> Text -> Either Text HttpIri
forall a b. a -> Either a b
Left (Text
"Not an authorised hierarchy")

-- | Generalize an HTTP IRI to IRI
iriFromHttpIri :: HttpIri -> Iri
iriFromHttpIri :: HttpIri -> Iri
iriFromHttpIri (HttpIri (Security Bool
secure) Host
host Port
port Path
path Query
query Fragment
fragment) =
  Scheme -> Hierarchy -> Query -> Fragment -> Iri
Iri Scheme
scheme Hierarchy
hierarchy Query
query Fragment
fragment
  where
    scheme :: Scheme
scheme =
      ByteString -> Scheme
Scheme (if Bool
secure then ByteString
"https" else ByteString
"http")
    hierarchy :: Hierarchy
hierarchy =
      Authority -> Path -> Hierarchy
AuthorisedHierarchy (UserInfo -> Host -> Port -> Authority
Authority UserInfo
MissingUserInfo Host
host Port
port) Path
path