module Page.GroupChest exposing (Model, Msg(..), init, refresh, update, view) import Api exposing (HttpResult, Loot) import Html exposing (..) import Html.Attributes exposing (..) import Html.Events exposing (..) import Page.Chest as Chest exposing (Chest) import Session exposing (Session, User(..)) import Set import Table import Utils exposing (renderIcon) type alias Model = { session : Session , loot : State , chest : Chest } type State = Loading | LoadError String | Loaded Loot getClaimsFromSession session = case Session.user session of Session.Player data -> if data.player.id /= 0 then data.claims -- TODO: The group and admin case should be impossible ! else [] Session.Admin -> [] init session = ( Model session Loading (Tuple.first <| Chest.update (Chest.showWithClaims <| getClaimsFromSession session) Chest.init ) , Cmd.map Internal <| Api.fetchLoot GotLoot Api.OfGroup ) view : Model -> ( Html Msg, List (Html Msg) ) view model = case model.loot of Loading -> ( text "" , [ p [ class "title" ] [ text "loading..." ] ] ) LoadError error -> ( text "" , [ p [ class "has-text-danger" ] [ text <| "Error : " ++ error ] ] ) Loaded loot -> ( Html.map Internal <| let ( isPlayer, isGroup ) = case Session.user model.session of Session.Admin -> ( False, False ) Session.Player data -> ( True, data.player.id == 0 ) in case ( model.chest, isPlayer && not isGroup ) of ( Chest.View _, True ) -> button [ class "button" , onClick (GotChestMsg <| Chest.claim (getClaimsFromSession model.session)) ] [ text "Demander" ] ( Chest.Claim _, True ) -> button [ class "button", onClick ConfirmGrab ] [ text "Valider" ] ( _, _ ) -> text "" , [ Chest.view model.chest loot |> Html.map (Internal << GotChestMsg) ] ) type Msg = Api Api.Msg | Internal InnerMsg type InnerMsg = GotLoot Api.ToChest (HttpResult Loot) | GotChestMsg Chest.Msg | ConfirmGrab refresh model = update (Internal <| GotChestMsg (Chest.intoMode (Chest.IntoViewWithClaims (getClaimsFromSession model.session)))) model update : Msg -> Model -> ( Model, Cmd Msg ) update msg model = case msg of Api apiMsg -> ( model, Cmd.none ) Internal ConfirmGrab -> case ( Session.user model.session, model.loot, model.chest ) of ( Session.Player data, Loaded loot, Chest.Claim _ ) -> ( model , Chest.confirmGrab data.player.id loot model.chest |> Cmd.map Api ) _ -> ( model, Cmd.none ) Internal innerMsg -> (case innerMsg of GotLoot _ (Ok loot) -> ( { model | loot = Loaded loot }, Cmd.none ) GotLoot _ (Err _) -> ( { model | loot = LoadError "Le chargement a échoué" }, Cmd.none ) GotChestMsg chestMsg -> Chest.update chestMsg model.chest |> updateChest model _ -> ( model, Cmd.none ) ) |> Tuple.mapSecond (Cmd.map Internal) updateChest model ( chestModel, chestCmd ) = ( { model | chest = chestModel } , Cmd.map GotChestMsg chestCmd )