use crate::value_estimation_team::indicators::bollingerband::bollingerband;

use super::{
    adx, dec, decimal_add, decimal_div, decimal_sub, duplicate_filter, ema, ema_macd,
    exists_record, get_server_epoch, insert_pre_suggested_coins, limit_order_sell, remove_keys,
    rsi, select_filled_buy_orders, stoch_rsi, supertrend, try_join_all, update_record3, AdxData,
    AllData, Arc, BollingerBandData, Client, ClientBuilder, Decimal, EmaData, ExchangeInfo,
    FilteredDataValue, HashMap, HashSet, MacdData, Mutex, RealtimePriceData, RoundingStrategy,
    RsiData, StochRsiData, SuperTrendArea, SuperTrendSignal, SupertrendData, ToPrimitive, TradeFee,
};

// BB lowerband + SuperTrend + StochRSI
// SuperTrend length: 20, multiplier: 1.5, BUY signal
// ADX(10, 10) < 25.0
pub async fn list_up_for_buy(
    alldata: &AllData,
) -> 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());

    // 1st 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());
    }

    // 4th filtering: 0.5% <= the average amplitude of the latest 10 30m candles <= 1.0%
    let mut keys_to_remove: HashSet<String> = HashSet::new();
    for (symbol, values) in &mut filtered_data {
        if alldata.rt_price_30m_vec.contains_key(symbol) {
            let rt_price_30m = alldata.rt_price_30m_vec.get(symbol).unwrap();
            let vec_len = rt_price_30m.len();

            if let Some(candles) = rt_price_30m.get(vec_len - 12..vec_len - 1) {
                let windows = candles.windows(2);
                let mut average_amplitude = 0.0;

                for window in windows {
                    average_amplitude += (window.last().unwrap().high_price
                        - window.last().unwrap().low_price)
                        / window.first().unwrap().close_price;
                }
                average_amplitude /= 10.0;

                if 0.005 <= average_amplitude && average_amplitude <= 0.01 {
                } else {
                    keys_to_remove.insert(symbol.clone());
                }
            } else {
                keys_to_remove.insert(symbol.clone());
            }
        } else {
            keys_to_remove.insert(symbol.clone());
        }
    }
    remove_keys(&mut filtered_data, keys_to_remove).await;

    // 2nd filtering: supertrend(ATR period 20, multiplier: 2, 30m close price)
    let mut keys_to_remove: HashSet<String> = HashSet::new();
    let server_epoch = get_server_epoch().await;
    let supertrend_30m_map =
        supertrend(20, 2.0, true, &alldata.rt_price_30m_vec, &filtered_data).await?;
    for (symbol, values) in &mut filtered_data {
        if let (Some(supertrend_vec), Some(rt_price_vec)) = (
            supertrend_30m_map.get(symbol),
            alldata.rt_price_30m_vec.get(symbol),
        ) {
            if supertrend_vec.last().unwrap().close_time == rt_price_vec.last().unwrap().close_time
                && rt_price_vec.last().unwrap().close_time > server_epoch
            {
                // input closetime, current_price
                values.closetime = rt_price_vec.last().unwrap().close_time;
                values.current_price = rust_decimal::prelude::FromPrimitive::from_f64(
                    rt_price_vec.last().unwrap().close_price,
                )
                .unwrap();

                // input stoploss
                let band_value: Decimal = rust_decimal::prelude::FromPrimitive::from_f64(
                    supertrend_vec.last().unwrap().band_value,
                )
                .unwrap();
                if supertrend_vec.last().unwrap().area == SuperTrendArea::DOWN
                    && supertrend_vec.last().unwrap().band_value
                        > values.current_price.to_f64().unwrap()
                {
                    values.stoploss = decimal_sub(
                        values.current_price,
                        decimal_sub(band_value, values.current_price),
                    );
                } else if supertrend_vec.last().unwrap().area == SuperTrendArea::UP
                    && supertrend_vec.last().unwrap().band_value
                        < values.current_price.to_f64().unwrap()
                {
                    values.stoploss = band_value;
                } else {
                    keys_to_remove.insert(symbol.clone());
                }
            } else {
                keys_to_remove.insert(symbol.clone());
            }
        } else {
            keys_to_remove.insert(symbol.clone());
        }
    }
    remove_keys(&mut filtered_data, keys_to_remove).await;

    // filtering: the latest 5 30m candle close prices > EMA 200
    let mut keys_to_remove: HashSet<String> = HashSet::new();
    let emas = ema(200, &alldata.rt_price_30m_vec, &filtered_data).await?;
    for (symbol, values) in &mut filtered_data {
        if emas.contains_key(symbol) && alldata.rt_price_30m_vec.contains_key(symbol) {
            let ema = emas.get(symbol).unwrap();
            let rt_price_30m = alldata.rt_price_30m_vec.get(symbol).unwrap();
            let rt_price_30m_len = rt_price_30m.len();
            let search_result = ema.binary_search_by_key(
                &alldata
                    .rt_price_30m_vec
                    .get(symbol)
                    .unwrap()
                    .last()
                    .unwrap()
                    .close_time,
                |EmaData {
                     ema_value,
                     close_time,
                 }| *close_time,
            );
            if search_result.is_ok_and(|x| {
                ema[search_result.unwrap()].ema_value
                    < rt_price_30m[rt_price_30m_len - 1].close_price
            }) && search_result.is_ok_and(|x| {
                ema[search_result.unwrap() - 1].ema_value
                    < rt_price_30m[rt_price_30m_len - 2].close_price
            }) && search_result.is_ok_and(|x| {
                ema[search_result.unwrap() - 2].ema_value
                    < rt_price_30m[rt_price_30m_len - 3].close_price
            }) && search_result.is_ok_and(|x| {
                ema[search_result.unwrap() - 3].ema_value
                    < rt_price_30m[rt_price_30m_len - 4].close_price
            }) && search_result.is_ok_and(|x| {
                ema[search_result.unwrap() - 4].ema_value
                    < rt_price_30m[rt_price_30m_len - 5].close_price
            }) {
            } else {
                keys_to_remove.insert(symbol.clone());
            }
        } else {
            keys_to_remove.insert(symbol.clone());
        }
    }
    remove_keys(&mut filtered_data, keys_to_remove).await;

    // filtering: 30m StochRSI (RSI_len: 10, StochRSI_len: 10, K: 3, D: 3) previous K < 5 && current K > previous K
    let mut keys_to_remove: HashSet<String> = HashSet::new();
    let stoch_rsis = stoch_rsi(10, 10, 3, 3, &alldata.rt_price_30m_vec, &filtered_data).await?;
    for (symbol, values) in &mut filtered_data {
        if alldata.rt_price_30m_vec.contains_key(symbol) && stoch_rsis.contains_key(symbol) {
            let stoch_rsi_vec = stoch_rsis.get(symbol).unwrap();
            let search_result = stoch_rsi_vec
                .iter()
                .position(|x| x.close_time == values.closetime);
            if search_result.is_some_and(|a| {
                stoch_rsi_vec[a - 1].k < 5.0 && stoch_rsi_vec[a].k > stoch_rsi_vec[a - 1].k
            }) {
            } else {
                keys_to_remove.insert(symbol.clone());
            }
        } else {
            keys_to_remove.insert(symbol.clone());
        }
    }
    remove_keys(&mut filtered_data, keys_to_remove).await;

    // filtering: 1d MACD (3, 7, 30) current MACD-signal > prev MACD-signal
    let mut keys_to_remove: HashSet<String> = HashSet::new();
    let macd_1d_map = ema_macd(3, 7, 30, &alldata.rt_price_1d_vec, &filtered_data).await?;
    for (symbol, values) in &mut filtered_data {
        if let (Some(macd_vec), Some(rt_price_vec)) =
            (macd_1d_map.get(symbol), alldata.rt_price_1d_vec.get(symbol))
        {
            if macd_vec.last().unwrap().close_time == rt_price_vec.last().unwrap().close_time
                && rt_price_vec.last().unwrap().close_time > server_epoch
            {
                if macd_vec[macd_vec.len() - 1].macd_value
                    - macd_vec[macd_vec.len() - 1].signal_value
                    > macd_vec[macd_vec.len() - 2].macd_value
                        - macd_vec[macd_vec.len() - 2].signal_value
                {
                    values.current_price = rust_decimal::prelude::FromPrimitive::from_f64(
                        rt_price_vec.last().unwrap().close_price,
                    )
                    .unwrap();
                    values.closetime = rt_price_vec.last().unwrap().close_time;
                } else {
                    keys_to_remove.insert(symbol.clone());
                }
            } else {
                keys_to_remove.insert(symbol.clone());
            }
        } else {
            keys_to_remove.insert(symbol.clone());
        }
    }
    remove_keys(&mut filtered_data, keys_to_remove).await;

    // filtering: the 2 previous ADX(10, 10)s decrease
    let mut keys_to_remove: HashSet<String> = HashSet::new();
    let adx_vec = adx(10, 10, &alldata.rt_price_30m_vec, &filtered_data).await?;
    for (symbol, values) in &mut filtered_data {
        if let Some(adx_vec) = adx_vec.get(symbol) {
            if let Some(last_idx) = adx_vec
                .iter()
                .position(|elem| elem.close_time == values.closetime)
            {
                if adx_vec[last_idx].adx < adx_vec[last_idx - 1].adx
                    && adx_vec[last_idx - 1].adx < adx_vec[last_idx - 2].adx
                {
                } else {
                    keys_to_remove.insert(symbol.clone());
                }
            } else {
                keys_to_remove.insert(symbol.clone());
            }
        } else {
            keys_to_remove.insert(symbol.clone());
        }
    }
    remove_keys(&mut filtered_data, keys_to_remove).await;

    let final_filtered_data = duplicate_filter(1, &filtered_data).await?;
    insert_pre_suggested_coins(1, false, &final_filtered_data).await;

    Ok(())
}

pub async fn list_up_for_sell(
    all_data: &AllData,
    exchange_info_map: &HashMap<String, ExchangeInfo>,
    trade_fee_map: &HashMap<String, TradeFee>,
) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
    let filled_buy_orders = select_filled_buy_orders(1).await?;

    if !filled_buy_orders.is_empty() {
        let client = ClientBuilder::new()
            .timeout(tokio::time::Duration::from_millis(5000))
            .build()
            .unwrap();
        let mut supertrend_vec: Vec<SupertrendData> = Vec::new();
        let server_epoch = get_server_epoch().await;

        let mut filtered_symbols: HashMap<String, FilteredDataValue> = HashMap::new();
        for element in &filled_buy_orders {
            filtered_symbols.insert(element.symbol.clone(), FilteredDataValue::new());
        }
        let supertrend_30m =
            supertrend(20, 2.0, true, &all_data.rt_price_30m_vec, &filtered_symbols).await?;
        let stoch_rsis =
            stoch_rsi(10, 10, 3, 3, &all_data.rt_price_30m_vec, &filtered_symbols).await?;
        for element in filled_buy_orders {
            if element.used_usdt >= dec!(10.0) {
                if let (
                    Some(exchange_info),
                    Some(tradefee),
                    Some(stoch_rsi),
                    Some(supertrend_vec),
                ) = (
                    exchange_info_map.get(&element.symbol),
                    trade_fee_map.get(&element.symbol),
                    stoch_rsis.get(&element.symbol),
                    supertrend_30m.get(&element.symbol),
                ) {
                    // update stoploss
                    let band_value: Decimal = rust_decimal::prelude::FromPrimitive::from_f64(
                        supertrend_vec.last().unwrap().band_value,
                    )
                    .unwrap();
                    if supertrend_vec.last().unwrap().area == SuperTrendArea::UP
                        && band_value > element.stoploss
                    {
                        let update_table_name = String::from("buy_ordered_coin_list");
                        let update_value = vec![(String::from("stoploss"), band_value.to_string())];
                        let update_condition = vec![(String::from("id"), element.id.to_string())];
                        update_record3(&update_table_name, &update_value, &update_condition)
                            .await
                            .unwrap();
                    }

                    let lot_step_size = exchange_info.stepsize;
                    let quote_commission_precision = exchange_info.quote_commission_precision;
                    let base_qty_to_be_ordered = element.base_qty_ordered.round_dp_with_strategy(
                        lot_step_size.normalize().scale(),
                        RoundingStrategy::ToZero,
                    );
                    let stoch_rsi_k = stoch_rsi.last().unwrap().k;
                    let stoch_rsi_k_prev = stoch_rsi[stoch_rsi.len() - 2].k;
                    let stoch_rsi_d = stoch_rsi.last().unwrap().d;
                    let stoch_rsi_d_prev = stoch_rsi[stoch_rsi.len() - 2].d;
                    if (element.is_long == 0 || element.is_long == 1)
                        && !element.current_price.is_zero()
                    {
                        if element.current_price <= element.stoploss {
                            limit_order_sell(
                                &element,
                                element.current_price,
                                base_qty_to_be_ordered,
                                &client,
                                &exchange_info_map,
                                &trade_fee_map,
                            )
                            .await;
                        } else if server_epoch - element.transact_time > (1_800_000) * 15 {
                            limit_order_sell(
                                &element,
                                element.current_price,
                                base_qty_to_be_ordered,
                                &client,
                                &exchange_info_map,
                                &trade_fee_map,
                            )
                            .await;
                        } else if element.pure_profit_percent > 3.0 {
                            limit_order_sell(
                                &element,
                                element.current_price,
                                base_qty_to_be_ordered,
                                &client,
                                &exchange_info_map,
                                &trade_fee_map,
                            )
                            .await;
                        } else if stoch_rsi_k >= 90.0
                            && (stoch_rsi_k < stoch_rsi_d && stoch_rsi_k_prev > stoch_rsi_d_prev)
                        {
                            limit_order_sell(
                                &element,
                                element.current_price,
                                base_qty_to_be_ordered,
                                &client,
                                &exchange_info_map,
                                &trade_fee_map,
                            )
                            .await;
                        }
                        // TODO: sell_count가 1일 때 적용하기
                        // else if (supertrend_vec
                        //     .last()
                        //     .unwrap()
                        //     .signal
                        //     .as_ref()
                        //     .is_some_and(|x| x.contains("SELL"))
                        //     || supertrend_vec.last().unwrap().area.contains("DOWN"))
                        //     && (supertrend_vec.last().unwrap().close_time > element.close_time)
                        // {
                        //     println!(
                        //         "SELL signal selling {} {:.2}",
                        //         element.symbol, element.pure_profit_percent
                        //     );
                        //     limit_order_sell(
                        //         &element,
                        //         element.current_price,
                        //         base_qty_to_be_ordered,
                        //         &client,
                        //         &exchange_info_vec,
                        //         &trade_fee_vec,
                        //     )
                        //     .await;
                        // }
                    }
                }
            }
        }
    }

    Ok(())
}
