module Text.Yahoo.InternalRS
  ( fromYahooRS
  , fromXmlRS ) where

import Text.XML.Light.Cursor 
  (Cursor, firstChild, fromContent, rights, current)

import Text.Yahoo.Internal
import Text.Yahoo.Types

buildResultRS :: Cursor -> String
buildResultRS c = case getElemCData id c of
  (Right s) -> s
  (Left _) -> ""
 
buildResultSetRS :: Cursor -> Either Error RSResultSet
buildResultSetRS c = case firstChild c of
  (Just fc) -> Right $ filter (/= "") $ 
     map (buildResultRS . fromContent) (current fc : rights fc)
  -- just return an empty list if no results, not an error
  Nothing -> Right []

queryValidRS :: RSQuery -> Bool
queryValidRS rsq = rsNumResults rsq >= 0 && rsNumResults rsq <= 50

fromXmlRS :: String -> Either Error RSResultSet
fromXmlRS = fromXml' buildResultSetRS

fromYahooRS :: Bool -> RSQuery -> IO (Either Error RSResultSet)
fromYahooRS = fromYahoo' fromXmlRS queryValidRS relatedBase spellingBase

{- Resource URLs -}
relatedBase :: String
relatedBase = "http://search.yahooapis.com/WebSearchService/V1/relatedSuggestion?"

spellingBase :: String
spellingBase = "http://search.yahooapis.com/WebSearchService/V1/spellingSuggestion?"