use std::collections::HashMap;
use crate::ship::items::ClientItemId;
use crate::entity::item::{Meseta, ItemEntityId, ItemDetail, ItemEntity, ItemType, InventoryEntity, InventoryItemEntity, EquippedEntity, ItemNote};
use std::cell::{RefMut, RefCell};
use std::ops::{Deref, DerefMut};
use std::convert::{From, Into};
use std::future::Future;
use std::pin::Pin;
use async_std::sync::{Arc, Mutex};
use std::borrow::BorrowMut;

use crate::ship::location::{AreaClient, RoomId};
use crate::entity::character::{CharacterEntity, CharacterEntityId, TechLevel};
use crate::entity::gateway::{EntityGateway, GatewayError};
use crate::entity::gateway::entitygateway::EntityGatewayTransaction;
use crate::entity::item::tool::{Tool, ToolType};
use crate::ship::items::state::{ItemState, ItemStateProxy, ItemStateAction, ItemAction, ItemStateError, FloorItem, InventoryItem, AddItemResult};

pub enum TriggerCreateItem {ItemAction, 
    Yes,
    No
}

/*
fn take_item_from_floor(character_id: CharacterEntityId, item_id: ClientItemId)
                        -> impl for<'a> Fn((ItemStateProxy<'a>, Box<dyn EntityGatewayTransaction>), ())
                                           -> Pin<Box<dyn Future<Output=Result<((ItemStateProxy, Box<dyn EntityGatewayTransaction>), 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 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, 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 take_item_from_floor<'a, F, Fut>(character_id: CharacterEntityId, item_id: ClientItemId) -> F
where
    F: Fn((ItemStateProxy<'a>, Box<dyn EntityGatewayTransaction>), ()) -> Fut,
    Fut: Future<Output=Result<((ItemStateProxy<'a>, Box<dyn EntityGatewayTransaction>), FloorItem), ItemStateError>> + Send
    //Fut: Result<impl Future<Output=((ItemStateProxy<'a>, Box<dyn EntityGatewayTransaction>), FloorItem)> + Send, ItemStateError>
    
{
    async move |(mut item_state, transaction): (ItemStateProxy<'a>, Box<dyn EntityGatewayTransaction>), _: ()| {
        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<'a, Fut>(character: &CharacterEntity)
                                           -> impl Fn((ItemStateProxy<'a>, Box<dyn EntityGatewayTransaction>), FloorItem) -> Fut
where
    Fut: Future<Output=Result<((ItemStateProxy<'a>, Box<dyn EntityGatewayTransaction>), TriggerCreateItem), ItemStateError>> + Send
{
    let character = character.clone();
    move |(mut item_state, transaction): (ItemStateProxy<'a>, Box<dyn EntityGatewayTransaction>), floor_item: FloorItem| {
        let character = character.clone();
        async move {
            let mut inventory = item_state.inventory(&character.id)?;

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

            let mut transaction = floor_item.with_mag(Ok(transaction), |mut transaction: Result<_, ItemStateError>, entity_id, _mag| {
                let character = character.clone();
                async move {
                    if let Ok(transaction) = &mut transaction {
                        transaction.gateway().change_mag_owner(&entity_id, &character).await?;
                    }
                    transaction
                }}).await?;

            let add_result = inventory.add_floor_item(floor_item)?;
            transaction.gateway().set_character_inventory(&character.id, &inventory.inventory.as_inventory_entity(&character.id)).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,
                }))
        }
    }
}
*/

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, 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(Ok(transaction), |mut transaction: Result<_, ItemStateError>, entity_id| {
                async move {
                    if let Ok(transaction) = &mut transaction {
                        transaction.gateway().add_item_note(&entity_id, ItemNote::Pickup {
                            character_id
                        }).await?;
                    }
                    transaction
                }}).await?;

            let mut transaction = floor_item.with_mag(Ok(transaction), |mut transaction: Result<_, ItemStateError>, entity_id, _mag| {
                let character = character.clone();
                async move {
                    if let Ok(transaction) = &mut transaction {
                        transaction.gateway().change_mag_owner(&entity_id, &character).await?;
                    }
                    transaction
                }}).await?;

            let add_result = inventory.add_floor_item(floor_item)?;
            transaction.gateway().set_character_inventory(&character.id, &inventory.inventory.as_inventory_entity(&character.id)).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,
                }))
        })
    }
}

/*
fn add_floor_item_to_inventory(character: &CharacterEntity)
                               -> impl for<'a> Fn((ItemStateProxy<'a>, Box<dyn EntityGatewayTransaction>), FloorItem)
                                                  -> Pin<Box<dyn Future<Output=Result<((ItemStateProxy, Box<dyn EntityGatewayTransaction>), 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(Ok(transaction), |mut transaction: Result<_, ItemStateError>, entity_id| {
                async move {
                    if let Ok(transaction) = &mut transaction {
                        transaction.gateway().add_item_note(&entity_id, ItemNote::Pickup {
                            character_id
                        }).await?;
                    }
                    transaction
                }}).await?;

            let mut transaction = floor_item.with_mag(Ok(transaction), |mut transaction: Result<_, ItemStateError>, entity_id, _mag| {
                let character = character.clone();
                async move {
                    if let Ok(transaction) = &mut transaction {
                        transaction.gateway().change_mag_owner(&entity_id, &character).await?;
                    }
                    transaction
                }}).await?;

            let add_result = inventory.add_floor_item(floor_item)?;
            transaction.gateway().set_character_inventory(&character.id, &inventory.inventory.as_inventory_entity(&character.id)).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,
                }))
        })
    }
}
*/

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

            transaction.gateway().set_character_inventory(&character_id, &inventory.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: &CharacterEntity)
                                      -> impl for<'a> Fn((ItemStateProxy<'a>, Box<dyn EntityGatewayTransaction>), InventoryItem)
                                                         -> Pin<Box<dyn Future<Output=Result<((ItemStateProxy, Box<dyn EntityGatewayTransaction>), ()), ItemStateError>> + Send + 'a>>
{
    let character = character.clone();
    move |(mut item_state, transaction), inventory_item| {
        let character = character.clone();
        Box::pin(async move {
            
        })
    }
}
*/

/*
pub async fn pick_up_item<'a, EG>(
    item_state: &'a mut ItemState,
    entity_gateway: &mut EG,
    character: &CharacterEntity,
    item_id: &ClientItemId)
    -> Result<TriggerCreateItem, ItemStateError>
where
    //'a: 'static,
    EG: EntityGateway,
{
    let result: Result<TriggerCreateItem, ItemStateError> = 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;
    Ok(result?)
}
*/

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,
{
    let result: Result<TriggerCreateItem, ItemStateError> = 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;
    Ok(result?)
}

pub async fn drop_item<EG>(
    item_state: &mut ItemState,
    entity_gateway: &mut EG,
    character: &CharacterEntity,
    item_id: &ClientItemId)
    -> Result<(), ItemStateError>
where
    //'a: 'static,
    EG: EntityGateway,
{
/*
    let result: Result<TriggerCreateItem, ItemStateError> = 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))
            .act(add_inventory_item_to_shared_floor(&character))
            .commit((item_state_proxy, transaction))
            .await?;
        item_state_proxy.commit();
        Ok((transaction, result))
    }).await;
    Ok(result?)
     */
    Ok(())
}