-- | This module provides functions for converting a full URL to just the
-- domain name or the TLD.
module YesWeScan.DomainName (domainName, topLevelDomain) where

import Data.Text (unpack)
import Network.URI (parseURI)
import Network.URI.TLD (parseTLDURI)

-- | Split an url into subdomain(s), domain, TLD.
splitTld :: String -> Maybe (String, String, String)
splitTld url =
    do uri <- parseURI url
       (sub,dom,tld) <- parseTLDURI uri
       return (unpack sub,unpack dom,unpack tld)

-- | Return the domain name.
domainName :: String -> String
domainName url =
    case splitTld url of
      Just (_,dom,tld) -> dom ++ "." ++ tld
      Nothing -> error "domainName: Invalid URI provided."

-- | Return just the TLD.
topLevelDomain :: String -> String
topLevelDomain url =
    case splitTld url of
      Just (_,_,tld) -> tld
      Nothing -> error "Invalid URI provided."
