use super::{
    adx, dec, decimal_add, decimal_div, decimal_mul, decimal_sub, duplicate_filter, ema, ema_macd,
    exists_record, get_current_price_decimal, 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,
};

// BUY conditions
// (1) ADX(10,10): increasing, ADX_current < 25
// (2) ADX(5,5): increasing, ADX_current < 40
// (3) RSI (5) < 75
// (4) SuperTrend(14, 2): UP Area
// stoploss: (not update) supertrend(14, 2) lowerband of UP area
// target price: (fixed) stoploss inverse x 3 times profit
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());

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

    // 1st filtering: the 2 previous ADX(10, 10)s increase, ADX < 25
    let mut keys_to_remove: HashSet<String> = HashSet::new();
    let adx_vec = adx(10, 10, &alldata.rt_price_1d_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.len() > 10
                    && adx_vec[last_idx].adx > adx_vec[last_idx - 1].adx
                    && adx_vec[last_idx - 1].adx > adx_vec[last_idx - 2].adx
                    && adx_vec[last_idx].adx < 25.0
                {
                } 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;
    println!("{}", filtered_data.keys().len());
    // 2nd filtering: the 2 previous ADX(5, 5)s increase, ADX < 40
    let mut keys_to_remove: HashSet<String> = HashSet::new();
    let adx_vec = adx(10, 10, &alldata.rt_price_1d_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.len() > 10
                    && adx_vec[last_idx].adx > adx_vec[last_idx - 1].adx
                    && adx_vec[last_idx - 1].adx > adx_vec[last_idx - 2].adx
                    && adx_vec[last_idx].adx < 40.0
                {
                } 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;

    // 3rd filtering: RSI 5 < 75.0
    let mut keys_to_remove: HashSet<String> = HashSet::new();
    let rsi_map = rsi(5, &alldata.rt_price_1d_vec, &filtered_data).await?;
    for (symbol, values) in &mut filtered_data {
        if let Some(rsi_vec) = rsi_map.get(symbol) {
            if let Some(last_idx) = rsi_vec
                .iter()
                .position(|elem| elem.close_time == values.closetime)
            {
                if rsi_vec[last_idx].rsi_value > 75.0 {
                    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;

    // 4th filtering: supertrend(ATR period 14, multiplier: 1.2, 1d close price)
    let mut keys_to_remove: HashSet<String> = HashSet::new();
    let server_epoch = get_server_epoch().await;
    let supertrend_1d_map =
        supertrend(14, 1.2, true, &alldata.rt_price_1d_vec, &filtered_data).await?;
    for (symbol, values) in &mut filtered_data {
        if let (Some(supertrend_vec), Some(rt_price_vec)) = (
            supertrend_1d_map.get(symbol),
            alldata.rt_price_1d_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 stoploss, target_price
                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
                    && supertrend_vec.last().unwrap().band_value
                        < values.current_price.to_f64().unwrap()
                {
                    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;
                    values.stoploss = band_value;
                    values.target_price = decimal_add(
                        decimal_mul(
                            decimal_sub(values.current_price, values.stoploss),
                            dec!(3.0),
                        ),
                        values.current_price,
                    );
                } 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;

    // limit buy price: 3 * abs(이전 3 개 중 최대값 제거 한 opclo 값 평균 - 현재 open 값) + 현재 open 값 > current_price
    let mut keys_to_remove: HashSet<String> = HashSet::new();
    let server_epoch = get_server_epoch().await;
    for (symbol, values) in &mut filtered_data {
        if let Some(rt_price_vec) = alldata.rt_price_1d_vec.get(symbol) {
            if rt_price_vec.last().unwrap().close_time > server_epoch && rt_price_vec.len() >= 6 {
                let mut opclo_vec: Vec<f64> = Vec::new();
                opclo_vec.push(rt_price_vec[rt_price_vec.len() - 2].opclo_price);
                opclo_vec.push(rt_price_vec[rt_price_vec.len() - 3].opclo_price);
                opclo_vec.push(rt_price_vec[rt_price_vec.len() - 4].opclo_price);
                opclo_vec.push(rt_price_vec[rt_price_vec.len() - 5].opclo_price);
                opclo_vec.push(rt_price_vec[rt_price_vec.len() - 6].opclo_price);
                let max_idx = opclo_vec.iter().position(|&x| {
                    x == *opclo_vec
                        .iter()
                        .max_by(|&a, &b| a.partial_cmp(b).unwrap())
                        .unwrap()
                });
                opclo_vec.remove(max_idx.unwrap());

                let mut mean = 0.0;
                for element in &opclo_vec {
                    mean += element;
                }
                mean /= opclo_vec.len() as f64;
                let current_price = rt_price_vec.last().unwrap().close_price;
                let difference = (mean - rt_price_vec.last().unwrap().open_price).abs();

                if current_price < rt_price_vec.last().unwrap().open_price + (3.0 * difference) {
                } 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(7, &filtered_data).await?;
    insert_pre_suggested_coins(7, false, &final_filtered_data).await;

    Ok(())
}

// (1) 15일 까지 지켜봄
// (2) 7일 까지는 target_price 까지 기다림
// (3) 8~15 까지는 target_price가 이루려는 profit percent의 절반 될 때까지 선형으로 줄어듦
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(7).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_1d =
            supertrend(14, 1.2, true, &all_data.rt_price_1d_vec, &filtered_symbols).await?;
        for element in filled_buy_orders {
            let mut is_sell = false;

            if element.used_usdt >= dec!(10.0) {
                if let (Some(exchange_info), Some(tradefee), Some(supertrend_vec)) = (
                    exchange_info_map.get(&element.symbol),
                    trade_fee_map.get(&element.symbol),
                    supertrend_1d.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 target_profit_percent = decimal_div(
                        decimal_sub(element.target_price, element.buy_price),
                        element.buy_price,
                    )
                    .to_f64()
                    .unwrap();
                    if (element.is_long == 0 || element.is_long == 1)
                        && !element.current_price.is_zero()
                    {
                        if element.current_price <= element.stoploss {
                            is_sell = true;
                        } else if element.current_price >= element.target_price {
                            is_sell = true;
                        } else if server_epoch - element.transact_time > (86_400_000) * 8
                            && (target_profit_percent != 0.0
                                && target_profit_percent.is_sign_positive()
                                && target_profit_percent * (13.0 / 14.0)
                                    <= element.pure_profit_percent)
                        {
                            is_sell = true;
                        } else if server_epoch - element.transact_time > (86_400_000) * 9
                            && (target_profit_percent != 0.0
                                && target_profit_percent.is_sign_positive()
                                && target_profit_percent * (12.0 / 14.0)
                                    <= element.pure_profit_percent)
                        {
                            is_sell = true;
                        } else if server_epoch - element.transact_time > (86_400_000) * 10
                            && (target_profit_percent != 0.0
                                && target_profit_percent.is_sign_positive()
                                && target_profit_percent * (11.0 / 14.0)
                                    <= element.pure_profit_percent)
                        {
                            is_sell = true;
                        } else if server_epoch - element.transact_time > (86_400_000) * 11
                            && (target_profit_percent != 0.0
                                && target_profit_percent.is_sign_positive()
                                && target_profit_percent * (10.0 / 14.0)
                                    <= element.pure_profit_percent)
                        {
                            is_sell = true;
                        } else if server_epoch - element.transact_time > (86_400_000) * 12
                            && (target_profit_percent != 0.0
                                && target_profit_percent.is_sign_positive()
                                && target_profit_percent * (9.0 / 14.0)
                                    <= element.pure_profit_percent)
                        {
                            is_sell = true;
                        } else if server_epoch - element.transact_time > (86_400_000) * 13
                            && (target_profit_percent != 0.0
                                && target_profit_percent.is_sign_positive()
                                && target_profit_percent * (8.0 / 14.0)
                                    <= element.pure_profit_percent)
                        {
                            is_sell = true;
                        } else if server_epoch - element.transact_time > (86_400_000) * 14
                            && (target_profit_percent != 0.0
                                && target_profit_percent.is_sign_positive()
                                && target_profit_percent * (1.0 / 2.0)
                                    <= element.pure_profit_percent)
                        {
                            // scaled selling with time up selling (6 days){
                            is_sell = true;
                        } else if server_epoch - element.transact_time > (86_400_000) * 15 {
                            // time up selling
                            is_sell = true;
                        }
                        // 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;
                        // }
                        if is_sell == true {
                            limit_order_sell(
                                &element,
                                element.current_price,
                                base_qty_to_be_ordered,
                                &client,
                                &exchange_info_map,
                                &trade_fee_map,
                            )
                            .await;
                        }
                    }
                }
            }
        }
    }

    Ok(())
}
