use crate::ship::items::ClientItemId;
use crate::entity::item::{Meseta, ItemNote};
use std::future::Future;
use std::pin::Pin;

use crate::ship::map::MapArea;
use crate::entity::character::{CharacterEntity, CharacterEntityId};
use crate::entity::gateway::{EntityGateway, EntityGatewayTransaction};
use crate::ship::items::state::{ItemState, ItemStateProxy, ItemStateAction, ItemAction, ItemStateError, FloorItem, InventoryItem, AddItemResult, FloorItemDetail,
                                StackedItemDetail, BankItem, BankItemDetail, InventoryItemDetail, IndividualItemDetail};
use crate::ship::items::apply_item::apply_item;
use crate::entity::item::{ItemDetail, ItemEntity, NewItemEntity};
use crate::entity::item::tool::Tool;
use crate::ship::shops::ShopItem;



pub enum TriggerCreateItem {
    Yes,
    No
}

fn take_item_from_floor(character_id: CharacterEntityId, item_id: ClientItemId)
                        -> impl for<'a> Fn((ItemStateProxy<'a>, Box<dyn EntityGatewayTransaction + 'a>), ())
                                               -> Pin<Box<dyn Future<Output=Result<((ItemStateProxy<'a>, Box<dyn EntityGatewayTransaction + 'a>), FloorItem), ItemStateError>> + Send + 'a>>
{
    move |(mut item_state, transaction), _| {
        Box::pin(async move {
            let mut floor = item_state.floor(&character_id)?;
            let item = floor.take_item(&item_id).ok_or(ItemStateError::NoFloorItem(item_id))?;
            item_state.set_floor(floor);

            Ok(((item_state, transaction), item))
        })
    }
}

fn add_floor_item_to_inventory(character: &CharacterEntity)
                               -> impl for<'a> Fn((ItemStateProxy<'a>, Box<dyn EntityGatewayTransaction + 'a>), FloorItem)
                                                  -> Pin<Box<dyn Future<Output=Result<((ItemStateProxy<'a>, Box<dyn EntityGatewayTransaction + 'a>), TriggerCreateItem), ItemStateError>> + Send + 'a>>
{
    let character = character.clone();
    move |(mut item_state, transaction), floor_item| {
        let character = character.clone();
        Box::pin(async move {
            let mut inventory = item_state.inventory(&character.id)?;

            let character_id = character.id;
            let transaction = floor_item.with_entity_id(transaction, |mut transaction, entity_id| {
                async move {
                    transaction.gateway().add_item_note(&entity_id, ItemNote::Pickup {
                        character_id
                    }).await?;
                    Ok(transaction)
                }}).await?;

            let mut transaction = floor_item.with_mag(transaction, |mut transaction, entity_id, _mag| {
                let character = character.clone();
                async move {
                    transaction.gateway().change_mag_owner(&entity_id, &character).await?;
                    Ok(transaction)
                }}).await?;

            let add_result = inventory.add_floor_item(floor_item)?;
            transaction.gateway().set_character_inventory(&character.id, &inventory.as_inventory_entity(&character.id)).await?;
            transaction.gateway().set_character_meseta(&character_id, inventory.meseta).await?;
            item_state.set_inventory(inventory);

            Ok(((item_state, transaction),
                match add_result {
                    AddItemResult::NewItem => TriggerCreateItem::Yes,
                    AddItemResult::AddToStack => TriggerCreateItem::No,
                    AddItemResult::Meseta => TriggerCreateItem::No,
                }))
        })
    }
}


pub async fn pick_up_item<EG>(
    item_state: &mut ItemState,
    entity_gateway: &mut EG,
    character: &CharacterEntity,
    item_id: &ClientItemId)
    -> Result<TriggerCreateItem, ItemStateError>
where
    EG: EntityGateway,
{
    entity_gateway.with_transaction(|transaction| async move {
        let item_state_proxy = ItemStateProxy::new(item_state);
        let ((item_state_proxy, transaction), result) = ItemStateAction::default()
            .act(take_item_from_floor(character.id, *item_id))
            .act(add_floor_item_to_inventory(character))
            .commit((item_state_proxy, transaction))
            .await?;
        item_state_proxy.commit();
        Ok((transaction, result))
    }).await
}

fn take_item_from_inventory(character_id: CharacterEntityId, item_id: ClientItemId, amount: u32)
                            -> impl for<'a> Fn((ItemStateProxy<'a>, Box<dyn EntityGatewayTransaction + 'a>), ())
                                               -> Pin<Box<dyn Future<Output=Result<((ItemStateProxy<'a>, Box<dyn EntityGatewayTransaction + 'a>), InventoryItem), ItemStateError>> + Send + 'a>>
{
    move |(mut item_state, mut transaction), _| {
        Box::pin(async move {
            let mut inventory = item_state.inventory(&character_id)?;
            let item = inventory.take_item(&item_id, amount).ok_or_else (|| ItemStateError::NoFloorItem(item_id))?;

            transaction.gateway().set_character_inventory(&character_id, &inventory.as_inventory_entity(&character_id)).await?;
            item_state.set_inventory(inventory);

            Ok(((item_state, transaction), item))
        })
    }
}


fn add_inventory_item_to_shared_floor(character_id: CharacterEntityId, map_area: MapArea, drop_position: (f32, f32, f32))
                                  -> impl for<'a> Fn((ItemStateProxy<'a>, Box<dyn EntityGatewayTransaction + 'a>), InventoryItem)
                                                     -> Pin<Box<dyn Future<Output=Result<((ItemStateProxy<'a>, Box<dyn EntityGatewayTransaction + 'a>), FloorItem), ItemStateError>> + Send + 'a>>
{
    move |(mut item_state, transaction), inventory_item| {
        Box::pin(async move {
            let transaction = inventory_item.with_entity_id(transaction, |mut transaction, entity_id| {
                async move {
                    transaction.gateway().add_item_note(&entity_id, ItemNote::PlayerDrop {
                        character_id,
                        map_area,
                        x: drop_position.0,
                        y: drop_position.1,
                        z: drop_position.2,
                    }).await?;
                    Ok(transaction)
                }}).await?;

            let mut floor = item_state.floor(&character_id)?;
            let floor_item = floor.add_inventory_item(inventory_item, map_area, drop_position).clone();
            item_state.set_floor(floor);

            Ok(((item_state, transaction), floor_item))
        })
    }
}

pub async fn drop_item<EG>(
    item_state: &mut ItemState,
    entity_gateway: &mut EG,
    character: &CharacterEntity,
    item_id: &ClientItemId,
    map_area: MapArea,
    drop_position: (f32, f32, f32))
    -> Result<FloorItem, ItemStateError>
where
    EG: EntityGateway,
{
    entity_gateway.with_transaction(|transaction| async move {
        let item_state_proxy = ItemStateProxy::new(item_state);
        let ((item_state_proxy, transaction), result) = ItemStateAction::default()
            .act(take_item_from_inventory(character.id, *item_id, 0))
            .act(add_inventory_item_to_shared_floor(character.id, map_area, drop_position))
            .commit((item_state_proxy, transaction))
            .await?;
        item_state_proxy.commit();
        Ok((transaction, result))
    }).await
}

pub async fn drop_partial_item<'a, EG>(
    item_state: &'a mut ItemState,
    entity_gateway: &mut EG,
    character: &CharacterEntity,
    item_id: &ClientItemId,
    map_area: MapArea,
    drop_position: (f32, f32),
    amount: u32)
    -> Result<FloorItem, ItemStateError>
where
    EG: EntityGateway,
{
    entity_gateway.with_transaction(|transaction| async move {
        let item_state_proxy = ItemStateProxy::new(item_state);
        let ((item_state_proxy, transaction), result) = ItemStateAction::default()
            .act(take_item_from_inventory(character.id, *item_id, amount))
            .act(add_inventory_item_to_shared_floor(character.id, map_area, (drop_position.0, 0.0, drop_position.1)))
            .commit((item_state_proxy, transaction))
            .await?;
        item_state_proxy.commit();
        Ok((transaction, result))
    }).await
}


fn take_meseta_from_inventory(character_id: CharacterEntityId, amount: u32)
                              -> impl for<'a> Fn((ItemStateProxy<'a>, Box<dyn EntityGatewayTransaction + 'a>), ())
                                                 -> Pin<Box<dyn Future<Output=Result<((ItemStateProxy<'a>, Box<dyn EntityGatewayTransaction + 'a>), ()), ItemStateError>> + Send + 'a>>
{
    move |(mut item_state, mut transaction), _| {
        Box::pin(async move {
            let mut inventory = item_state.inventory(&character_id)?;
            inventory.remove_meseta(amount)?;
            transaction.gateway().set_character_meseta(&character_id, inventory.meseta).await?;

            Ok(((item_state, transaction), ()))
        })
    }
}

fn add_meseta_to_shared_floor(character_id: CharacterEntityId, amount: u32, map_area: MapArea, drop_position: (f32, f32))
                              -> impl for<'a> Fn((ItemStateProxy<'a>, Box<dyn EntityGatewayTransaction + 'a>), ())
                                                 -> Pin<Box<dyn Future<Output=Result<((ItemStateProxy<'a>, Box<dyn EntityGatewayTransaction + 'a>), FloorItem), ItemStateError>> + Send + 'a>>
{

    move |(mut item_state, transaction), _| {
        Box::pin(async move {
            let floor_item = FloorItem {
                item_id: item_state.new_item_id()?,
                item: FloorItemDetail::Meseta(Meseta(amount)),
                map_area: map_area,
                x: drop_position.0,
                y: 0.0,
                z: drop_position.1,
            };

            let mut floor = item_state.floor(&character_id)?;
            let floor_item = floor.add_item(floor_item).clone();
            item_state.set_floor(floor);

            Ok(((item_state, transaction), floor_item))
        })
    }
}

pub async fn drop_meseta<'a, EG>(
    item_state: &'a mut ItemState,
    entity_gateway: &mut EG,
    character: &CharacterEntity,
    map_area: MapArea,
    drop_position: (f32, f32),
    amount: u32)
    -> Result<FloorItem, ItemStateError>
where
    EG: EntityGateway,
{
    entity_gateway.with_transaction(|transaction| async move {
        let item_state_proxy = ItemStateProxy::new(item_state);
        let ((item_state_proxy, transaction), result) = ItemStateAction::default()
            .act(take_meseta_from_inventory(character.id, amount))
            .act(add_meseta_to_shared_floor(character.id, amount, map_area, drop_position))
            .commit((item_state_proxy, transaction))
            .await?;
        item_state_proxy.commit();
        Ok((transaction, result))
    }).await
}


fn take_meseta_from_bank(character_id: CharacterEntityId, amount: u32)
                         -> impl for<'a> Fn((ItemStateProxy<'a>, Box<dyn EntityGatewayTransaction + 'a>), ())
                                            -> Pin<Box<dyn Future<Output=Result<((ItemStateProxy<'a>, Box<dyn EntityGatewayTransaction + 'a>), ()), ItemStateError>> + Send + 'a>>
{
    move |(mut item_state, mut transaction), _| {
        Box::pin(async move {
            let mut bank = item_state.bank(&character_id)?;
            bank.remove_meseta(amount)?;
            transaction.gateway().set_bank_meseta(&character_id, &bank.name, bank.meseta).await?;

            Ok(((item_state, transaction), ()))
        })
    }
}

fn add_meseta_from_bank_to_inventory(character_id: CharacterEntityId, amount: u32)
                         -> impl for<'a> Fn((ItemStateProxy<'a>, Box<dyn EntityGatewayTransaction + 'a>), ())
                                            -> Pin<Box<dyn Future<Output=Result<((ItemStateProxy<'a>, Box<dyn EntityGatewayTransaction + 'a>), ()), ItemStateError>> + Send + 'a>>
{
    move |(mut item_state, mut transaction), _| {
        Box::pin(async move {
            let mut inventory = item_state.inventory(&character_id)?;
            inventory.add_meseta_no_overflow(amount)?;
            transaction.gateway().set_character_meseta(&character_id, inventory.meseta).await?;

            Ok(((item_state, transaction), ()))
        })
    }
}


pub async fn withdraw_meseta<'a, EG>(
    item_state: &'a mut ItemState,
    entity_gateway: &mut EG,
    character: &CharacterEntity,
    amount: u32)
    -> Result<(), ItemStateError>
where
    EG: EntityGateway,
{
    entity_gateway.with_transaction(|transaction| async move {
        let item_state_proxy = ItemStateProxy::new(item_state);
        let ((item_state_proxy, transaction), result) = ItemStateAction::default()
            .act(take_meseta_from_bank(character.id, amount))
            .act(add_meseta_from_bank_to_inventory(character.id, amount))
            .commit((item_state_proxy, transaction))
            .await?;
        item_state_proxy.commit();
        Ok((transaction, result))
    }).await
}

fn add_meseta_to_bank(character_id: CharacterEntityId, amount: u32)
                      -> impl for<'a> Fn((ItemStateProxy<'a>, Box<dyn EntityGatewayTransaction + 'a>), ())
                                         -> Pin<Box<dyn Future<Output=Result<((ItemStateProxy<'a>, Box<dyn EntityGatewayTransaction + 'a>), ()), ItemStateError>> + Send + 'a>>
{
    move |(mut item_state, mut transaction), _| {
        Box::pin(async move {
            let mut bank = item_state.bank(&character_id)?;
            bank.add_meseta(amount)?;
            transaction.gateway().set_bank_meseta(&character_id, &bank.name, bank.meseta).await?;

            Ok(((item_state, transaction), ()))
        })
    }
}

pub async fn deposit_meseta<'a, EG>(
    item_state: &'a mut ItemState,
    entity_gateway: &mut EG,
    character: &CharacterEntity,
    amount: u32)
    -> Result<(), ItemStateError>
where
    EG: EntityGateway,
{
    entity_gateway.with_transaction(|transaction| async move {
        let item_state_proxy = ItemStateProxy::new(item_state);
        let ((item_state_proxy, transaction), result) = ItemStateAction::default()
            .act(take_meseta_from_inventory(character.id, amount))
            .act(add_meseta_to_bank(character.id, amount))
            .commit((item_state_proxy, transaction))
            .await?;
        item_state_proxy.commit();
        Ok((transaction, ()))
    }).await
}

fn take_item_from_bank(character_id: CharacterEntityId, item_id: ClientItemId, amount: u32)
                        -> impl for<'a> Fn((ItemStateProxy<'a>, Box<dyn EntityGatewayTransaction + 'a>), ())
                                               -> Pin<Box<dyn Future<Output=Result<((ItemStateProxy<'a>, Box<dyn EntityGatewayTransaction + 'a>), BankItem), ItemStateError>> + Send + 'a>>
{
    move |(mut item_state, mut transaction), _| {
        Box::pin(async move {
            let mut bank = item_state.bank(&character_id)?;
            let item = bank.take_item(&item_id, amount).ok_or_else(|| ItemStateError::NoBankItem(item_id))?;
            transaction.gateway().set_character_bank(&character_id, &bank.as_bank_entity(), &bank.name).await?;
            item_state.set_bank(bank);

            Ok(((item_state, transaction), item))
        })
    }
}

fn add_bank_item_to_inventory(character: &CharacterEntity)
                              -> impl for<'a> Fn((ItemStateProxy<'a>, Box<dyn EntityGatewayTransaction + 'a>), BankItem)
                                                 -> Pin<Box<dyn Future<Output=Result<((ItemStateProxy<'a>, Box<dyn EntityGatewayTransaction + 'a>), InventoryItem), ItemStateError>> + Send + 'a>>
{
    let character = character.clone();
    move |(mut item_state, transaction), bank_item| {
        let character = character.clone();
        Box::pin(async move {
            let bank_name = item_state.bank(&character.id)?.name;
            let mut inventory = item_state.inventory(&character.id)?;

            let character_id = character.id;
            let transaction = bank_item.with_entity_id(transaction, |mut transaction, entity_id| {
                let bank_name = bank_name.clone();
                async move {
                    transaction.gateway().add_item_note(&entity_id, ItemNote::Withdraw {
                        character_id,
                        bank: bank_name,
                    }).await?;
                    Ok(transaction)
                }}).await?;

            let inventory_item = InventoryItem {
                item_id: bank_item.item_id,
                item: match bank_item.item {
                    BankItemDetail::Individual(individual_item) => InventoryItemDetail::Individual(individual_item),
                    BankItemDetail::Stacked(stacked_item) => InventoryItemDetail::Stacked(stacked_item),
                },
            };

            let mut transaction = inventory_item.with_mag(transaction, |mut transaction, entity_id, _mag| {
                let character = character.clone();
                async move {
                    transaction.gateway().change_mag_owner(&entity_id, &character).await?;
                    Ok(transaction)
                }}).await?;

            inventory.add_item(inventory_item.clone())?;
            transaction.gateway().set_character_inventory(&character.id, &inventory.as_inventory_entity(&character.id)).await?;
            item_state.set_inventory(inventory);

            Ok(((item_state, transaction), inventory_item))
        })
    }
}

pub async fn withdraw_item<'a, EG>(
    item_state: &'a mut ItemState,
    entity_gateway: &mut EG,
    character: &CharacterEntity,
    item_id: &ClientItemId,
    amount: u32)
    -> Result<InventoryItem, ItemStateError>
where
    EG: EntityGateway,
{
    entity_gateway.with_transaction(|transaction| async move {
        let item_state_proxy = ItemStateProxy::new(item_state);
        let ((item_state_proxy, transaction), result) = ItemStateAction::default()
            .act(take_item_from_bank(character.id, *item_id, amount))
            .act(add_bank_item_to_inventory(&character))
            .commit((item_state_proxy, transaction))
            .await?;
        item_state_proxy.commit();
        Ok((transaction, result))
    }).await
}

fn add_inventory_item_to_bank(character_id: CharacterEntityId)
                              -> impl for<'a> Fn((ItemStateProxy<'a>, Box<dyn EntityGatewayTransaction + 'a>), InventoryItem)
                                                 -> Pin<Box<dyn Future<Output=Result<((ItemStateProxy<'a>, Box<dyn EntityGatewayTransaction + 'a>), ()), ItemStateError>> + Send + 'a>>
{
    move |(mut item_state, transaction), inventory_item| {
        Box::pin(async move {
            let mut bank = item_state.bank(&character_id)?;
            let bank_name = bank.name.clone();
            let mut transaction = inventory_item.with_entity_id(transaction, move |mut transaction, entity_id| {
                let bank_name = bank_name.clone();
                async move {
                    transaction.gateway().add_item_note(&entity_id, ItemNote::Deposit {
                        character_id,
                        bank: bank_name,
                    }).await?;
                    Ok(transaction)
                }}).await?;

            bank.add_inventory_item(inventory_item)?;

            transaction.gateway().set_character_bank(&character_id, &bank.as_bank_entity(), &bank.name).await?;
            item_state.set_bank(bank);


            Ok(((item_state, transaction), ()))
        })
    }
}

pub async fn deposit_item<'a, EG> (
    item_state: &'a mut ItemState,
    entity_gateway: &mut EG,
    character: &CharacterEntity,
    item_id: &ClientItemId,
    amount: u32)
    -> Result<(), ItemStateError>
where
    EG: EntityGateway,
{
    entity_gateway.with_transaction(|transaction| async move {
        let item_state_proxy = ItemStateProxy::new(item_state);
        let ((item_state_proxy, transaction), result) = ItemStateAction::default()
            .act(take_item_from_inventory(character.id, *item_id, amount))
            .act(add_inventory_item_to_bank(character.id))
            .commit((item_state_proxy, transaction))
            .await?;
        item_state_proxy.commit();
        Ok((transaction, result))
    }).await
}

fn equip_inventory_item(character_id: CharacterEntityId, item_id: ClientItemId, equip_slot: u8)
                        -> impl for<'a> Fn((ItemStateProxy<'a>, Box<dyn EntityGatewayTransaction + 'a>), ())
                                           -> Pin<Box<dyn Future<Output=Result<((ItemStateProxy<'a>, Box<dyn EntityGatewayTransaction + 'a>), ()), ItemStateError>> + Send + 'a>>
{
    move |(mut item_state, mut transaction), _| {
        Box::pin(async move {
            let mut inventory = item_state.inventory(&character_id)?;
            inventory.equip(&item_id, equip_slot);
            transaction.gateway().set_character_equips(&character_id, &inventory.as_equipped_entity()).await?;
            item_state.set_inventory(inventory);

            Ok(((item_state, transaction), ()))
        })
    }
}

pub async fn equip_item<'a, EG> (
    item_state: &'a mut ItemState,
    entity_gateway: &mut EG,
    character: &CharacterEntity,
    item_id: &ClientItemId,
    equip_slot: u8,
) -> Result<(), ItemStateError>
where
    EG: EntityGateway,
{
    entity_gateway.with_transaction(|transaction| async move {
        let item_state_proxy = ItemStateProxy::new(item_state);
        let ((item_state_proxy, transaction), result) = ItemStateAction::default()
            .act(equip_inventory_item(character.id, *item_id, equip_slot))
            .commit((item_state_proxy, transaction))
            .await?;
        item_state_proxy.commit();
        Ok((transaction, result))
    }).await
}


fn unequip_inventory_item(character_id: CharacterEntityId, item_id: ClientItemId)
                          -> impl for<'a> Fn((ItemStateProxy<'a>, Box<dyn EntityGatewayTransaction + 'a>), ())
                                             -> Pin<Box<dyn Future<Output=Result<((ItemStateProxy<'a>, Box<dyn EntityGatewayTransaction + 'a>), ()), ItemStateError>> + Send + 'a>>
{
    move |(mut item_state, mut transaction), _| {
        Box::pin(async move {
            let mut inventory = item_state.inventory(&character_id)?;
            inventory.unequip(&item_id);
            transaction.gateway().set_character_equips(&character_id, &inventory.as_equipped_entity()).await?;
            item_state.set_inventory(inventory);

            Ok(((item_state, transaction), ()))
        })
    }
}

pub async fn unequip_item<'a, EG> (
    item_state: &'a mut ItemState,
    entity_gateway: &mut EG,
    character: &CharacterEntity,
    item_id: &ClientItemId,
) -> Result<(), ItemStateError>
where
    EG: EntityGateway,
{
    entity_gateway.with_transaction(|transaction| async move {
        let item_state_proxy = ItemStateProxy::new(item_state);
        let ((item_state_proxy, transaction), result) = ItemStateAction::default()
            .act(unequip_inventory_item(character.id, *item_id))
            .commit((item_state_proxy, transaction))
            .await?;
        item_state_proxy.commit();
        Ok((transaction, result))
    }).await
}


fn sort_inventory_items(character_id: CharacterEntityId, item_ids: Vec<ClientItemId>)
                        -> impl for<'a> Fn((ItemStateProxy<'a>, Box<dyn EntityGatewayTransaction + 'a>), ())
                                           -> Pin<Box<dyn Future<Output=Result<((ItemStateProxy<'a>, Box<dyn EntityGatewayTransaction + 'a>), ()), ItemStateError>> + Send + 'a>>
{
    move |(mut item_state, mut transaction), _| {
        let item_ids = item_ids.clone();
        Box::pin(async move {
            let mut inventory = item_state.inventory(&character_id)?;
            inventory.sort(&item_ids);
            transaction.gateway().set_character_inventory(&character_id, &inventory.as_inventory_entity(&character_id)).await?;
            item_state.set_inventory(inventory);

            Ok(((item_state, transaction), ()))
        })
    }
}

pub async fn sort_inventory<'a, EG> (
    item_state: &'a mut ItemState,
    entity_gateway: &mut EG,
    character: &CharacterEntity,
    item_ids: Vec<ClientItemId>,
) -> Result<(), ItemStateError>
where
    EG: EntityGateway,
{
    entity_gateway.with_transaction(|transaction| async move {
        let item_state_proxy = ItemStateProxy::new(item_state);
        let ((item_state_proxy, transaction), result) = ItemStateAction::default()
            .act(sort_inventory_items(character.id, item_ids))
            .commit((item_state_proxy, transaction))
            .await?;
        item_state_proxy.commit();
        Ok((transaction, result))
    }).await
}


fn use_consumed_item(character: CharacterEntity)
                      -> impl for<'a> Fn((ItemStateProxy<'a>, Box<dyn EntityGatewayTransaction + 'a>), InventoryItem)
                                         -> Pin<Box<dyn Future<Output=Result<((ItemStateProxy<'a>, Box<dyn EntityGatewayTransaction + 'a>), CharacterEntity), ItemStateError>> + Send + 'a>>
{
    move |(mut item_state, transaction), inventory_item| {
        let mut character = character.clone();
        Box::pin(async move {
            let mut transaction = inventory_item.with_entity_id(transaction, |mut transaction, entity_id| {
                async move {
                    transaction.gateway().add_item_note(&entity_id, ItemNote::Consumed).await?;
                    Ok(transaction)
                }}).await?;

            apply_item(&mut item_state, transaction.gateway(), &mut character, inventory_item).await?;

            Ok(((item_state, transaction), character))
        })
    }
}

pub async fn use_item<'a, EG> (
    item_state: &'a mut ItemState,
    entity_gateway: &mut EG,
    character: &mut CharacterEntity,
    item_id: &ClientItemId,
    amount: u32,
) -> Result<(), ItemStateError>
where
    EG: EntityGateway,
{
    entity_gateway.with_transaction(|transaction| async move {
        let item_state_proxy = ItemStateProxy::new(item_state);
        let ((item_state_proxy, transaction), new_character) = ItemStateAction::default()
            .act(take_item_from_inventory(character.id, *item_id, amount))
            .act(use_consumed_item(character.clone()))
            .commit((item_state_proxy, transaction))
            .await?;
        item_state_proxy.commit();
        *character = new_character;
        Ok((transaction, ()))
    }).await
}

fn feed_mag_item(character: CharacterEntity, mag_item_id: ClientItemId)
                      -> impl for<'a> Fn((ItemStateProxy<'a>, Box<dyn EntityGatewayTransaction + 'a>), InventoryItem)
                                         -> Pin<Box<dyn Future<Output=Result<((ItemStateProxy<'a>, Box<dyn EntityGatewayTransaction + 'a>), CharacterEntity), ItemStateError>> + Send + 'a>>
{
    move |(mut item_state, transaction), tool| {
        let character = character.clone();
        Box::pin(async move {
            let mut inventory = item_state.inventory(&character.id)?;
            let mag_entity = inventory.get_by_client_id_mut(&mag_item_id)
                .ok_or_else(|| ItemStateError::InvalidItemId(mag_item_id))?
                .item
                .as_individual_mut()
                .ok_or_else(|| ItemStateError::NotAMag(mag_item_id))?;
            let mag_entity_id = mag_entity.entity_id;

            let mut transaction = tool.with_entity_id(transaction, |mut transaction, entity_id| {
                async move {
                    transaction.gateway().add_item_note(&entity_id, ItemNote::FedToMag {
                        //character_id: character.id,
                        mag: mag_entity_id,
                    }).await?;
                    transaction.gateway().feed_mag(&mag_entity_id, &entity_id).await?;
                    Ok(transaction)
                }}).await?;

            let food_tool = tool
                .item
                .stacked()
                .ok_or_else(|| ItemStateError::NotMagFood(tool.item_id))?
                .tool
                .tool;

            let mag_entity = mag_entity
                .as_mag_mut()
                .ok_or_else(|| ItemStateError::NotAMag(mag_item_id))?;

            mag_entity.feed(food_tool);

            transaction.gateway().set_character_inventory(&character.id, &inventory.as_inventory_entity(&character.id)).await?;
            item_state.set_inventory(inventory);

            Ok(((item_state, transaction), character))
        })
    }
}


pub async fn feed_mag<'a, EG> (
    item_state: &'a mut ItemState,
    entity_gateway: &mut EG,
    character: &CharacterEntity,
    mag_item_id: &ClientItemId,
    tool_item_id: &ClientItemId,
) -> Result<(), ItemStateError>
where
    EG: EntityGateway,
{
    entity_gateway.with_transaction(|transaction| async move {
        let item_state_proxy = ItemStateProxy::new(item_state);
        let ((item_state_proxy, transaction), _) = ItemStateAction::default()
            .act(take_item_from_inventory(character.id, *tool_item_id, 1))
            .act(feed_mag_item(character.clone(), *mag_item_id))
            .commit((item_state_proxy, transaction))
            .await?;
        item_state_proxy.commit();
        Ok((transaction, ()))
    }).await
}


fn add_bought_item_to_inventory<'a>(character_id: CharacterEntityId,
                                    shop_item: &'a (dyn ShopItem + Send + Sync),
                                    item_id: ClientItemId,
                                    amount: u32)
                                    -> impl Fn((ItemStateProxy<'a>, Box<dyn EntityGatewayTransaction + 'a>), ())
                                               -> Pin<Box<dyn Future<Output=Result<((ItemStateProxy<'a>, Box<dyn EntityGatewayTransaction + 'a>), InventoryItem), ItemStateError>> + Send + 'a>>
{
    move |(mut item_state, mut transaction), _| {
        Box::pin(async move {
            let mut inventory = item_state.inventory(&character_id)?;
            let bought_item = shop_item.as_item();

            let inventory_item = match bought_item {
                ItemDetail::Tool(tool) if tool.is_stackable() => {
                    let mut item_entities = Vec::new();
                    for _ in 0..amount {
                        let item_entity = transaction.gateway().create_item(NewItemEntity {
                            item: ItemDetail::Tool(tool),
                        }).await?;
                        transaction.gateway().add_item_note(&item_entity.id, ItemNote::BoughtAtShop {
                            character_id: character_id,
                        }).await?;
                        item_entities.push(item_entity);
                    }

                    let inventory_item = InventoryItem {
                        item_id,
                        item: InventoryItemDetail::Stacked(StackedItemDetail {
                            entity_ids: item_entities.into_iter().map(|i| i.id).collect(),
                            tool: tool,
                        })
                    };
                    inventory.add_item(inventory_item)?.1
                },
                item_detail => {
                    let item_entity = transaction.gateway().create_item(NewItemEntity {
                        item: item_detail.clone(),
                    }).await?;
                    transaction.gateway().add_item_note(&item_entity.id, ItemNote::BoughtAtShop {
                        character_id: character_id,
                    }).await?;

                    let inventory_item = InventoryItem {
                        item_id,
                        item: InventoryItemDetail::Individual(IndividualItemDetail {
                            entity_id: item_entity.id,
                            item: item_detail,
                        })
                    };
                    inventory.add_item(inventory_item)?.1
                },
            };

            transaction.gateway().set_character_inventory(&character_id, &inventory.as_inventory_entity(&character_id)).await?;
            item_state.set_inventory(inventory);
            Ok(((item_state, transaction), inventory_item))
        })
    }
}

pub async fn buy_shop_item<'a, EG> (
    item_state: &'a mut ItemState,
    entity_gateway: &mut EG,
    character: &CharacterEntity,
    shop_item: &'a (dyn ShopItem + Send + Sync),
    item_id: ClientItemId,
    amount: u32,
) -> Result<InventoryItem, ItemStateError>
where
    EG: EntityGateway,
{
    let item_price = shop_item.price() as u32 * amount;
    entity_gateway.with_transaction(|transaction| async move {
        let item_state_proxy = ItemStateProxy::new(item_state);
        let ((item_state_proxy, transaction), result) = ItemStateAction::default()
            .act(take_meseta_from_inventory(character.id, item_price))
            .act(add_bought_item_to_inventory(character.id, shop_item, item_id, amount))
            .commit((item_state_proxy, transaction))
            .await?;
        item_state_proxy.commit();
        Ok((transaction, result))
    }).await
}