module Draft exposing (Draft, Pick, PickCard, decode)

import Json.Decode as Decode exposing (Decoder)
import Json.Decode.Pipeline as Decode
import Zipper


type alias Draft =
    Zipper.Zipper Pick


type alias Pick =
    { chosen : PickCard
    , available : List PickCard
    }


type alias PickCard =
    { name : String
    , frontImage : String
    , backImage : Maybe String
    }


decode : String -> Result String Draft
decode x =
    Decode.decodeString decodeDraft x |> Result.mapError Decode.errorToString


decodeDraft : Decoder Draft
decodeDraft =
    Decode.field "picks" (Decode.list decodePick)
        |> Decode.map Zipper.fromList
        |> Decode.andThen
            (\z ->
                case z of
                    Just x ->
                        Decode.succeed x

                    Nothing ->
                        Decode.fail "No picks in draft data"
            )


decodePick : Decoder Pick
decodePick =
    Decode.succeed Pick
        |> Decode.required "pick" decodeCard
        |> Decode.required "available" (Decode.list decodeCard)


decodeCard : Decoder PickCard
decodeCard =
    Decode.succeed PickCard
        |> Decode.required "name" Decode.string
        |> Decode.required "image_url" Decode.string
        |> Decode.required
            "url_back"
            (Decode.string
                |> Decode.map
                    (\s ->
                        if s == "" then
                            Nothing

                        else
                            Just s
                    )
            )
