-- |
-- Module:      $Header$
-- Description: Encoding hostnames according to IDNA2008
-- Copyright:   Copyright © 2011 Jon Kristensen
-- License:     BSD3
--
-- Maintainer:  jon.kristensen@pontarius.org
-- Stability:   unstable
-- Portability: portable
--
-- Makes a Unicode hostname internationalized. The code is currently prototyped
-- and untested.


module Data.Text.IDNA2008 (toASCII) where

import Data.List (intersperse)
import Data.List.Split (splitOn)
import Data.Maybe (fromJust)
import Data.Text.Punycode (encode)


-- |
-- Converts a Unicode hostname into an internationalized ASCII hostname.

toASCII :: String -> Maybe String

toASCII t = if Nothing `elem` encodedLabels
            then Nothing
            else Just encodedHostname
    where

        labels :: [String]
        labels = splitOn "." t

        encodedLabels :: [Maybe String]
        encodedLabels = map encode labels

        encodedHostname :: String
        encodedHostname = concat $ intersperse "." $ map fromJust encodedLabels