module History exposing (..)

import Data exposing (Id)
import Url exposing (Url)
import Url.Parser
import Url.Parser.Query
import Dict exposing (Dict)

type History
    = Home
    | Interview Id
    | Person Id
    | Search (Maybe String) String

parseHistory : Url -> Maybe History
parseHistory url =
    let
        url_ : Url
        url_ = { url | path = "/" }

        getQuery : String -> Maybe String
        getQuery tag = Maybe.andThen identity
            <| Url.Parser.parse (Url.Parser.query <| Url.Parser.Query.string tag) url_

    in Maybe.andThen
        (\page ->
            case page of
                "home" -> Just Home
                "interview" ->
                    Maybe.map Interview <| getQuery "page-id"
                "person" ->
                    Maybe.map Person <| getQuery "page-id"
                "search" ->
                    Maybe.map
                        (Search <| getQuery "page-title")
                    <| getQuery "page-query"
                _ -> Nothing
        )
        <| getQuery "page"

encodeHistory : History -> Dict String String
encodeHistory history =
    Dict.fromList
    <| case history of
        Home ->
            [ ("page", "home") ]
        Interview id ->
            [ ("page", "interview")
            , ("page-id", id)
            ]
        Person id ->
            [ ("page", "person")
            , ("page-id", id)
            ]
        Search Nothing query ->
            [ ("page", "search")
            , ("page-query", query)
            ]
        Search (Just title) query ->
            [ ("page", "search")
            , ("page-title", title)
            , ("page-query", query)
            ]

getTitle : History -> String
getTitle history =
    case history of
        Home -> "Home"
        Interview id -> "Interview " ++ id
        Person id -> "Person " ++ id
        Search (Just title) _ -> title
        Search Nothing query -> "Search '" ++ String.left 20 query ++ "'"
