module API exposing (getSets)

import Http
import Json.Decode as Decode


apiUrl : String
apiUrl =
    "http://localhost:8000"


makeApiUrl : List String -> String
makeApiUrl paths =
    apiUrl ++ "/" ++ String.join "/" paths


getSets : (Result String (List String) -> msg) -> Cmd msg
getSets onSuccess =
    Http.get
        { url = makeApiUrl [ "sets" ]
        , expect =
            Http.expectJson (Result.mapError httpErrorToString >> onSuccess)
                (Decode.field "sets"
                    (Decode.list Decode.string)
                )
        }


httpErrorToString : Http.Error -> String
httpErrorToString error =
    case error of
        Http.BadUrl url ->
            "Bad URL: " ++ url

        Http.Timeout ->
            "Timeout"

        Http.NetworkError ->
            "Network error"

        Http.BadStatus status ->
            "Bad status: " ++ String.fromInt status

        Http.BadBody body ->
            "Bad body: " ++ body
