use crate::ship::items::ClientItemId;
use crate::entity::item::Meseta;

use crate::ship::ship::SendShipPacket;
use crate::ship::map::MapArea;
use crate::entity::character::{CharacterEntity, CharacterEntityId};
use crate::entity::gateway::{EntityGateway, EntityGatewayTransaction};
use crate::ship::items::state::{ItemState, ItemStateProxy, IndividualItemDetail};
use crate::ship::items::itemstateaction::{ItemStateAction, ItemAction};
use crate::ship::items::inventory::InventoryItem;
use crate::ship::items::floor::FloorItem;
use crate::entity::item::ItemModifier;
use crate::ship::shops::ShopItem;
use crate::ship::trade::TradeItem;
use crate::ship::location::AreaClient;
use crate::ship::drops::ItemDrop;

use crate::ship::items::actions;

use log::warn;

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

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, anyhow::Error>
where
    EG: EntityGateway + 'static,
{
    entity_gateway.with_transaction(|transaction| async move {
        let item_state_proxy = ItemStateProxy::new(item_state.clone());
        let ((item_state_proxy, transaction), result) = ItemStateAction::default()
            .act(actions::take_item_from_inventory(character.id, *item_id, 0))
            .act(actions::add_inventory_item_to_shared_floor(character.id, map_area, drop_position))
            .commit((item_state_proxy, transaction))
            .await?;
        item_state_proxy.commit().await;
        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, anyhow::Error>
where
    EG: EntityGateway + 'static,
{
    entity_gateway.with_transaction(|transaction| async move {
        let item_state_proxy = ItemStateProxy::new(item_state.clone());
        let ((item_state_proxy, transaction), result) = ItemStateAction::default()
            .act(actions::take_item_from_inventory(character.id, *item_id, amount))
            .act(actions::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().await;
        Ok((transaction, result))
    }).await
}



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, anyhow::Error>
where
    EG: EntityGateway + 'static,
{
    entity_gateway.with_transaction(|transaction| async move {
        let item_state_proxy = ItemStateProxy::new(item_state.clone());
        let ((item_state_proxy, transaction), result) = ItemStateAction::default()
            .act(actions::take_meseta_from_inventory(character.id, amount))
            .act(actions::add_meseta_to_shared_floor(character.id, amount, map_area, drop_position))
            .commit((item_state_proxy, transaction))
            .await?;
        item_state_proxy.commit().await;
        Ok((transaction, result))
    }).await
}


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


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


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, anyhow::Error>
where
    EG: EntityGateway + 'static,
{
    entity_gateway.with_transaction(|transaction| async move {
        let item_state_proxy = ItemStateProxy::new(item_state.clone());
        let ((item_state_proxy, transaction), result) = ItemStateAction::default()
            .act(actions::take_item_from_bank(character.id, *item_id, amount))
            //.act(bank_item_to_inventory_item)
            //.act(add_item_to_inventory)
            .act(actions::add_bank_item_to_inventory(character))
            .commit((item_state_proxy, transaction))
            .await?;
        item_state_proxy.commit().await;
        Ok((transaction, result))
    }).await
}


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

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<(), anyhow::Error>
where
    EG: EntityGateway + 'static,
{
    entity_gateway.with_transaction(|transaction| async move {
        let item_state_proxy = ItemStateProxy::new(item_state.clone());
        let ((item_state_proxy, transaction), result) = ItemStateAction::default()
            .act(actions::equip_inventory_item(character.id, *item_id, equip_slot))
            .commit((item_state_proxy, transaction))
            .await?;
        item_state_proxy.commit().await;
        Ok((transaction, result))
    }).await
}


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


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


pub async fn use_item<'a, EG> (
    item_state: &'a mut ItemState,
    entity_gateway: &mut EG,
    character: &mut CharacterEntity,
    area_client: AreaClient,
    item_id: &ClientItemId,
    amount: u32,
) -> Result<Vec<SendShipPacket>, anyhow::Error>
where
    EG: EntityGateway + 'static,
{
    entity_gateway.with_transaction(|transaction| async move {
        let item_state_proxy = ItemStateProxy::new(item_state.clone());
        let ((item_state_proxy, transaction), (pkts, new_character)) = ItemStateAction::default()
            .act(actions::take_item_from_inventory(character.id, *item_id, amount))
            .act(actions::use_consumed_item(character))
            .act(actions::fork(
                actions::foreach(actions::apply_item_action_packets(character.id, area_client)),
                actions::apply_item_action_character(character)
            ))
            .commit((item_state_proxy, transaction))
            .await?;
        item_state_proxy.commit().await;

        *character = new_character;
        Ok((transaction, pkts.into_iter().flatten().collect()))
    }).await
}


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<(), anyhow::Error>
where
    EG: EntityGateway + 'static,
{
    entity_gateway.with_transaction(|transaction| async move {
        let item_state_proxy = ItemStateProxy::new(item_state.clone());
        let ((item_state_proxy, transaction), _) = ItemStateAction::default()
            .act(actions::take_item_from_inventory(character.id, *tool_item_id, 1))
            .act(actions::feed_mag_item(character.clone(), *mag_item_id))
            .commit((item_state_proxy, transaction))
            .await?;
        item_state_proxy.commit().await;
        Ok((transaction, ()))
    }).await
}


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, anyhow::Error>
where
    EG: EntityGateway + 'static,
{
    let item_price = shop_item.price() as u32 * amount;
    entity_gateway.with_transaction(|transaction| async move {
        let item_state_proxy = ItemStateProxy::new(item_state.clone());
        let ((item_state_proxy, transaction), result) = ItemStateAction::default()
            .act(actions::take_meseta_from_inventory(character.id, item_price))
            //.act(bought_item_to_inventory_item)
            //.act(add_item_to_inventory)
            .act(actions::add_bought_item_to_inventory(character.id, shop_item, item_id, amount))
            .commit((item_state_proxy, transaction))
            .await?;
        item_state_proxy.commit().await;
        Ok((transaction, result))
    }).await
}


pub async fn sell_item<'a, EG> (
    item_state: &'a mut ItemState,
    entity_gateway: &mut EG,
    character: &CharacterEntity,
    item_id: ClientItemId,
    amount: u32,
) -> Result<InventoryItem, anyhow::Error>
where
    EG: EntityGateway + 'static,
{
    entity_gateway.with_transaction(|transaction| async move {
        let item_state_proxy = ItemStateProxy::new(item_state.clone());
        let ((item_state_proxy, transaction), result) = ItemStateAction::default()
            .act(actions::take_item_from_inventory(character.id, item_id, amount))
            .act(actions::sell_inventory_item(character.id))
            .commit((item_state_proxy, transaction))
            .await?;
        item_state_proxy.commit().await;
        Ok((transaction, result))
    }).await
}
pub async fn trade_items<'a, EG> (
    item_state: &'a mut ItemState,
    entity_gateway: &mut EG,
    p1: (&AreaClient, &CharacterEntity, &Vec<TradeItem>, Meseta),
    p2: (&AreaClient, &CharacterEntity, &Vec<TradeItem>, Meseta))
    -> Result<(Vec<InventoryItem>, Vec<InventoryItem>), anyhow::Error>
where
    EG: EntityGateway + 'static,
{
    let p1_trade_items = p1.2
        .iter()
        .map(|item| {
            match item {
                TradeItem::Individual(item_id) => (*item_id, 1),
                TradeItem::Stacked(item_id, amount) => (*item_id, *amount as u32),
            }
        })
        .collect();
    let p2_trade_items = p2.2
        .iter()
        .map(|item| {
            match item {
                TradeItem::Individual(item_id) => (*item_id, 1),
                TradeItem::Stacked(item_id, amount) => (*item_id, *amount as u32),
            }
        })
        .collect();
    entity_gateway.with_transaction(|mut transaction| async move {
        let p1_id = p1.1.id;
        let p2_id = p2.1.id;
        let trade = transaction.gateway().create_trade(&p1_id, &p2_id).await?;
        let item_state_proxy = ItemStateProxy::new(item_state.clone());
        let ((item_state_proxy, transaction), p1_removed_items) = ItemStateAction::default()
            .act(actions::iterate(p1_trade_items, move |p1_trade_item| actions::take_item_from_inventory(p1_id, p1_trade_item.0, p1_trade_item.1) ))
            .act(actions::foreach(actions::assign_new_item_id()))
            .commit((item_state_proxy, transaction))
            .await?;
        let ((item_state_proxy, transaction), p2_removed_items) = ItemStateAction::default()
            .act(actions::iterate(p2_trade_items, move |p2_trade_item| actions::take_item_from_inventory(p2_id, p2_trade_item.0, p2_trade_item.1) ))
            .act(actions::foreach(actions::assign_new_item_id()))
            .commit((item_state_proxy, transaction))
            .await?;

        let ((item_state_proxy, transaction), p2_new_items) = ItemStateAction::default()
            .act(actions::insert(p1_removed_items))
            .act(actions::foreach(actions::add_item_to_inventory(p2.1.clone())))
            .act(actions::record_trade(trade.id, p1_id, p2_id))
            .commit((item_state_proxy, transaction))
            .await?;
        let ((item_state_proxy, transaction), p1_new_items) = ItemStateAction::default()
            .act(actions::insert(p2_removed_items))
            .act(actions::foreach(actions::add_item_to_inventory(p1.1.clone())))
            .act(actions::record_trade(trade.id, p2_id, p1_id))
            .commit((item_state_proxy, transaction))
            .await?;

        let ((item_state_proxy, transaction), _) = ItemStateAction::default()
            .act(actions::take_meseta_from_inventory(p1_id, p1.3.0))
            .act(actions::take_meseta_from_inventory(p2_id, p2.3.0))
            .act(actions::add_meseta_to_inventory(p1_id, p2.3.0))
            .act(actions::add_meseta_to_inventory(p2_id, p1.3.0))
            .commit((item_state_proxy, transaction))
            .await?;

            item_state_proxy.commit().await;
        Ok((transaction, (p1_new_items, p2_new_items)))
    }).await
}


pub async fn take_meseta<'a, EG> (
    item_state: &'a mut ItemState,
    entity_gateway: &mut EG,
    character_id: &CharacterEntityId,
    meseta: Meseta)
    -> Result<(), anyhow::Error>
where
    EG: EntityGateway + 'static,
{
    entity_gateway.with_transaction(|transaction| async move {
        let item_state_proxy = ItemStateProxy::new(item_state.clone());
        let ((item_state_proxy, transaction), _) = ItemStateAction::default()
            .act(actions::take_meseta_from_inventory(*character_id, meseta.0))
            .commit((item_state_proxy, transaction))
            .await?;

            item_state_proxy.commit().await;
        Ok((transaction, ()))
    }).await
}

pub async fn enemy_drops_item<'a, EG> (
    item_state: &'a mut ItemState,
    entity_gateway: &mut EG,
    character_id: CharacterEntityId,
    item_drop: ItemDrop)
    -> Result<FloorItem, anyhow::Error>
where
    EG: EntityGateway + 'static,
{
    entity_gateway.with_transaction(|transaction| async move {
        let item_state_proxy = ItemStateProxy::new(item_state.clone());
        let ((item_state_proxy, transaction), floor_item) = ItemStateAction::default()
            .act(actions::convert_item_drop_to_floor_item(character_id, item_drop))
            .act(actions::add_item_to_local_floor(character_id))
            .commit((item_state_proxy, transaction))
            .await?;

            item_state_proxy.commit().await;
        Ok((transaction, floor_item))
    }).await
}


pub async fn apply_modifier<'a, EG> (
    item_state: &'a mut ItemState,
    entity_gateway: &mut EG,
    character: &CharacterEntity,
    item_id: ClientItemId,
    modifier: ItemModifier)
    -> Result<IndividualItemDetail, anyhow::Error>
where
    EG: EntityGateway + 'static,
{
    entity_gateway.with_transaction(|transaction| async move {
        let item_state_proxy = ItemStateProxy::new(item_state.clone());
        let ((item_state_proxy, transaction), item) = ItemStateAction::default()
            .act(actions::take_item_from_inventory(character.id, item_id, 1))
            .act(actions::apply_modifier_to_inventory_item(modifier))
            .act(actions::add_item_to_inventory(character.clone()))
            .act(actions::as_individual_item())
            .commit((item_state_proxy, transaction))
            .await?;

            item_state_proxy.commit().await;
        Ok((transaction, item))
    }).await
}