module Page.GroupChest exposing (Model, Msg(..), init, update, view) import Api exposing (HttpResult, Loot) import Bulma as B import Chest exposing (Chest) import Html exposing (..) import Html.Attributes exposing (..) import Html.Events exposing (..) import Session exposing (Session, User(..)) type alias Model = { session : Session , loot : State , chest : Chest } type State = Loading | LoadError String | Loaded Loot getClaimsFromSession session = case Session.user session of Player data -> if data.player.id /= 0 then data.claims -- TODO: The group and admin case should be impossible ! else [] 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 Admin _ -> ( False, False ) Player data -> ( True, data.player.id == 0 ) in case ( model.chest, isPlayer && not isGroup ) of ( Chest.View _, True ) -> B.btn (GotChestMsg <| Chest.claim (getClaimsFromSession model.session)) { text = "Demander", icon = "fas fa-praying-hands", color = "is-primary" } ( Chest.Claim _, True ) -> B.confirmButtons ConfirmGrab (GotChestMsg Chest.show) ( _, _ ) -> 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 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 ( Player data, Loaded loot, Chest.Claim _ ) -> ( model , Chest.confirmGrab data.player.id loot model.chest |> Cmd.map Api ) _ -> ( model, Cmd.none ) Internal innerMsg -> Tuple.mapSecond (Cmd.map Internal) <| 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 |> Tuple.mapBoth (\chest -> { model | chest = chest }) (Cmd.map GotChestMsg) _ -> ( model, Cmd.none )