use crate::value_estimation_team::{datapoints::price_data::CandleType, indicators::wiliams_percent_r};

use super::{
    adx, dec, decimal_add, decimal_div, decimal_mul, decimal_sub, dema, duplicate_filter, ema,
    ema_macd, exists_record, get_server_epoch, heatmap_volume,
    insert_pre_suggested_coins, limit_order_sell, remove_keys, rsi, select_filled_buy_orders,
    stoch_rsi, supertrend, tema, try_join_all, update_record3, wiliams_percent_r, AdxData, AllData,
    Arc, BollingerBandData, Client, ClientBuilder, Decimal, DemaData, EmaData, ExchangeInfo,
    FilteredDataValue, HashMap, HashSet, HeatMapLevel, HeatmapVolumeData, MacdData, Mutex,
    RealtimePriceData, RoundingStrategy, RsiData, StochRsiData, SuperTrendArea, SuperTrendSignal,
    SupertrendData, TemaData, ToPrimitive, TradeFee, WiliamsPercentR, future_duplicate_filter, insert_future_coins, get_current_price_decimal
};

use crate::future::{Position, FuturesExchangeInfo};
use crate::future::table_mgmt::select_filled_positions;
use crate::future::order::{limit_order_close, TimeInForce};

// BUY conditions
pub async fn list_up_for_buy(
    alldata: &AllData,
    future_exchange_info_map: &HashMap<String, FuturesExchangeInfo>
) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
    // print rt_price for debugging
    // let a = alldata.rt_price_30m_vec.iter().position(|a| a.0 == "BTCUSDT");
    // println!("BTCUSDT: {:?}", alldata.rt_price_30m_vec[a.unwrap()].1.last().unwrap());

    // basic filtering: filtering valid trade pair
    let mut filtered_data: HashMap<String, FilteredDataValue> = HashMap::new();
    for symbol in &alldata.valid_symbol_vec {
        filtered_data.insert(symbol.clone(), FilteredDataValue::new());
    }
    
    // current Tema(15) < current Tema(60)
    // let mut keys_to_remove: HashSet<String> = HashSet::new();
    // let tema_15 = tema(15, &alldata.rt_price_1m_vec, &filtered_data).await?;
    // let tema_60 = tema(60, &alldata.rt_price_1m_vec, &filtered_data).await?;
    // let server_epoch = get_server_epoch().await;
    // for (symbol, values) in &mut filtered_data {
    //     let mut do_buy = false;
    //     if let (Some(tema15_vec), Some(tema60_vec)) = (tema_15.get(symbol), tema_60.get(symbol)) {
    //         if tema15_vec.len() > 10
    //             && tema60_vec.len() > 10
    //             && tema15_vec.last().unwrap().close_time == tema60_vec.last().unwrap().close_time
    //             && tema15_vec.last().unwrap().close_time > server_epoch
    //             && tema60_vec.last().unwrap().close_time > server_epoch
    //         {
    //             if tema15_vec.last().unwrap().tema_value > tema60_vec.last().unwrap().tema_value {
    //                 do_buy = true;
    //             } 
    //         } 
    //     }
    //     if do_buy == false {
    //         keys_to_remove.insert(symbol.clone());
    //     }
    // }
    // remove_keys(&mut filtered_data, keys_to_remove).await;

    // Heatmap volume: filtering close price with Extra High is over the previous candle from 30 previous candles
    // let mut keys_to_remove: HashSet<String> = HashSet::new();
    // let heatmap_volumes = heatmap_volume(
    //     60,
    //     60,
    //     4.0,
    //     2.5,
    //     1.0,
    //     -0.5,
    //     &filtered_data,
    //     &alldata.rt_price_1m_vec,
    // )
    // .await?;
    // let server_epoch = get_server_epoch().await;
    // for (symbol, values) in &mut filtered_data {
    //     let mut do_buy = false;
    //     if let (Some(heatmap_volume_vec), Some(rt_price_vec), Some(rt_price_vec_30m)) = (heatmap_volumes.get(symbol), alldata.rt_price_1m_vec.get(symbol), alldata.rt_price_30m_vec.get(symbol)) {
    //         if heatmap_volume_vec.len() > 100
    //         && heatmap_volume_vec.last().unwrap().close_time > server_epoch 
    //         && rt_price_vec.last().unwrap().close_time == heatmap_volume_vec.last().unwrap().close_time 
    //         && heatmap_volume_vec[heatmap_volume_vec.len()-2].heatmap_level == HeatMapLevel::ExtraHigh
    //         && rt_price_vec[rt_price_vec.len()-2].candle_type == CandleType::DOWN {
    //             let current_price: Decimal = rust_decimal::prelude::FromPrimitive::from_f64(
    //                 rt_price_vec_30m.last().unwrap().close_price,
    //             )
    //             .unwrap();
    //             values.closetime = heatmap_volume_vec.last().unwrap().close_time;
    //             values.current_price = current_price;
    //             do_buy = true;
    //         }
    //     } 
        
    //     if do_buy == false {
    //         keys_to_remove.insert(symbol.clone());
    //     }
    // }
    // remove_keys(&mut filtered_data, keys_to_remove).await;

    // StochRSI (RSI_len: 30, StochRSI_len: 30, K: 2, D: 2) K_current < 70, K_prev < 70, K_prev_1 < 70
    let server_epoch = get_server_epoch().await;
    let mut keys_to_remove: HashSet<String> = HashSet::new();
    let stoch_rsis = stoch_rsi(30, 30, 2, 2, &alldata.rt_price_1m_vec, &filtered_data).await?;
    for (symbol, values) in &mut filtered_data {
        let mut do_buy = false;
        let price_and_closetime = get_current_price_decimal(&symbol, &alldata.rt_price_1m_vec).await;
        if let (Some(stoch_rsi_vec), Some(current_info)) = (stoch_rsis.get(symbol), price_and_closetime) {
            if server_epoch < current_info.1 {
                let search_result = stoch_rsi_vec
                .iter()
                .position(|x| x.close_time == current_info.1);
                if stoch_rsi_vec.len() > 10
                    && search_result.is_some_and(|a| {
                            stoch_rsi_vec[a].k > 20.0
                            && stoch_rsi_vec[a].k > stoch_rsi_vec[a].d
                            && stoch_rsi_vec[a - 1].k < 20.0
                            && stoch_rsi_vec[a - 2].k < 20.0
                            && stoch_rsi_vec[a - 3].k < 20.0
                            && stoch_rsi_vec[a - 4].k < 20.0
                    })
                {
                    values.closetime = current_info.1;
                    values.current_price = current_info.0;
                    do_buy = true;
                } 
            }
        }
        
        if do_buy == false {
            keys_to_remove.insert(symbol.clone());
        }
    }
    remove_keys(&mut filtered_data, keys_to_remove).await;

    let final_filtered_data = future_duplicate_filter(&filtered_data, &future_exchange_info_map).await?;
    insert_future_coins(Position::Long, server_epoch, &final_filtered_data).await?;

    Ok(())
}

pub async fn list_up_for_sell(alldata: &AllData) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
    let filled_positions = select_filled_positions().await?;

    let client = ClientBuilder::new()
        .timeout(tokio::time::Duration::from_millis(5000))
        .build()
        .unwrap();
    let server_epoch = get_server_epoch().await;
    let mut filtered_symbols: HashMap<String, FilteredDataValue> = HashMap::new();
    for element in &filled_positions {
        filtered_symbols.insert(element.symbol.clone(), FilteredDataValue::new());
    }
    let server_epoch = get_server_epoch().await;
    let stoch_rsis = stoch_rsi(30, 30, 2, 2, &alldata.rt_price_1m_vec, &filtered_symbols).await?;
    
    for element in filled_positions {
        if let Some(stoch_rsis_vec) = stoch_rsis.get(&element.symbol) {
            let mut over_turned = false;
            let mut is_sell = false;
            if stoch_rsis_vec.len() > 10 {
                if stoch_rsis_vec.last().unwrap().close_time > server_epoch 
                && stoch_rsis_vec[stoch_rsis.len()-1].k < stoch_rsis_vec[stoch_rsis.len()-1].d 
                && stoch_rsis_vec[stoch_rsis.len()-2].k > stoch_rsis_vec[stoch_rsis.len()-2].d {
                    over_turned = true;
                }

                // TODO: BNB 코인이 있으면
                // let base_qty_to_be_ordered =
                //     element.base_qty_ordered.round_dp_with_strategy(
                //         lot_step_size.normalize().scale(),
                //         RoundingStrategy::ToZero,
                //     );
                // TODO: BNB 코인이 없으면

                if !element.current_price.is_zero() {
                    if element.pure_profit_percent >= 0.6 {
                        is_sell = true;
                    } else if element.pure_profit_percent <= -0.8 {
                        is_sell = true;
                    } else if server_epoch - element.transact_time >= (300_000) * 1 {
                        // time up selling
                        is_sell = true;
                    } else if over_turned == true {
                        is_sell = true;
                    }
                
                    if is_sell == true {
                        limit_order_close(
                            &element,
                            TimeInForce::Gtc,
                            element.current_price,
                            element.base_qty_ordered,
                            &client
                        )
                        .await;
                    }
                }
            }
        }
    }

    Ok(())
}
