use derive_more::{Display, Error};
use super::{Foundation, FoundationSequence};
use crate::card::{Card, Rank};
use crate::card_sequence::Sequenced as _;
use crate::piles::{Pile as _, PileMut as _};
use crate::{action, undo};
#[derive(Debug)]
pub struct Action(pub Card);
#[derive(Debug)]
pub struct Value;
#[derive(Debug, Display, Error)]
pub enum Error {
#[display(fmt = "The card does not follow the top card of the foundation")]
DoesNotFollow,
#[display(fmt = "The foundation is empty but the card is not an ace")]
RequiresAce,
}
impl action::Action for Action {
type State<'s> = ();
type Value = Value;
type Error = Error;
}
impl action::Target<Action> for Foundation {
fn update(&mut self, Action(card): Action, _: ()) -> Result<Value, Error> {
if let Some(foundation_top_card) = self.pile.cards().last().copied() {
[foundation_top_card, card]
.is_sequential::<FoundationSequence>()
.map_err(|_| Error::DoesNotFollow)?;
} else if card.rank != Rank::Ace {
return Err(Error::RequiresAce);
}
self.pile.place_one(card);
Ok(Value)
}
}
impl undo::Target<Value> for Foundation {
fn revert(&mut self, _: Value) {
self.pile.take_exactly_one();
}
}