use std::future::Future;
use std::pin::Pin;
use crate::components::{BiddingBox, BiddingTable, Hand};
use crate::use_app_context;
use crate::utils::ok_json;
use anyhow::Context;
use gloo_net::http::Request;
use log::info;
use protocol::bridge_engine::{
Bid, BiddingState, BiddingStatePlayerView, GameStatePlayerView,
PlayStatePlayerView,
};
use yew::prelude::*;
#[function_component(OnlineTable)]
pub fn online_table(props: &OnlineTableProps) -> Html {
let ctx = use_app_context();
let table_state: UseStateHandle> =
use_state(|| None);
let update_table_state = {
let table_state = table_state.clone();
let props = props.clone();
|| {
Box::pin(async move {
// let table_state = table_state.clone();
let props = props.clone();
let response =
Request::get(&format!("/api/table/{}", props.table.id))
.send()
.await
.context("fetching table data")?;
let table = ok_json(response).await?;
table_state.set(Some(table));
Ok(())
})
as Pin>>>
}
};
{
let ctx = ctx.clone();
let update_table_state = update_table_state.clone();
use_effect_with_deps(
move |_| {
ctx.spawn_async(async move {
update_table_state().await?;
Ok(())
});
|| ()
},
(),
);
}
let on_bid = {
let ctx = ctx.clone();
let props = props.clone();
let update_table_state = update_table_state.clone();
Callback::from(move |bid| {
let update_table_state = update_table_state.clone();
info!("Bid clicked: {:?}", bid);
ctx.spawn_async(async move {
let bid_response = Request::post(&format!(
"/api/table/{}/bid",
props.table.id
))
.json(&bid)?
.send()
.await
.context("submitting bid")?;
let () = ok_json(bid_response).await?;
update_table_state().await?;
Ok(())
});
})
};
let leave_table = {
let ctx = ctx.clone();
Callback::from(move |_| {
ctx.leave_table();
})
};
let center = match &*table_state {
Some(GameStatePlayerView::Bidding(bidding)) =>
bidding_view(bidding, on_bid),
Some(GameStatePlayerView::Playing(playing)) => todo!(),
None => html! { {"Loading table"}
},
};
html! {
<>
p<>{ format!("This is table {}", props.table.id) }
{ "Leave table" }
{ center }
>
}
}
#[derive(PartialEq, Properties, Clone)]
pub struct OnlineTableProps {
pub table: protocol::Table,
}
pub fn bidding_view(
bidding: &BiddingStatePlayerView,
on_bid: Callback,
) -> Html {
html! {
<>
{ format!("It is {:?} to bid", bidding.bidding.current_bidder()) }
{ "Table view" }
{ format!("{:#?}", bidding) }
>
}
}