use super::{
    dec, decimal_add, decimal_sub, ema, exists_record, insert_pre_suggested_coins,
    limit_order_sell, rsi, select_filled_buy_orders, stoch_rsi, supertrend, try_join_all, AllData,
    Arc, Client, ClientBuilder, Decimal, EmaData, ExchangeInfo, FilteredData, Mutex,
    RealtimePriceData, RoundingStrategy, RsiData, StochRsiData, SupertrendData, TradeFee, update_record3, adx, AdxData, server_epoch, MacdData, ema_macd
};

// Triple SuperTrend strategy
// 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: lookup tables if the tradepair is already there
    let inspect_table_name_1 = String::from("buy_ordered_coin_list");
    let inspect_table_name_2 = String::from("sell_ordered_coin_list");
    let inspect_table_name_3 = String::from("pre_suggested_coin_list");
    let inspect_table_name_4 = String::from("suggested_coin_list");

    let mut filtered_data_1st: Vec<FilteredData> = Vec::new();
    let mut filtered_data_1st_arc: Arc<Mutex<Vec<FilteredData>>> =
        Arc::new(Mutex::new(filtered_data_1st));
    let mut task_vec = Vec::new();

    for symbol in &alldata.valid_symbol_vec {
        let mut exists_condition_build = String::from("symbol=\'");
        exists_condition_build.push_str(symbol.as_str());
        exists_condition_build.push_str("\' AND registerer=");
        exists_condition_build.push_str(5.to_string().as_str());
        // exists_condition_build.push_str("\' AND close_time=");
        // exists_condition_build.push_str(element.1.to_string().as_str());
        let exists_condition = Some(exists_condition_build);
        let exists_condition_c = exists_condition.clone();
        let inspect_table_name_1_c = inspect_table_name_1.clone();
        let inspect_table_name_2_c = inspect_table_name_2.clone();
        let inspect_table_name_3_c = inspect_table_name_3.clone();
        let inspect_table_name_4_c = inspect_table_name_4.clone();
        let symbol_c = symbol.clone();
        let filtered_data_1st_arc_c = Arc::clone(&filtered_data_1st_arc);
        task_vec.push(tokio::spawn(async move {
            let mut filtered_data = FilteredData::new();
            let inspect_result_1 =
                exists_record(&inspect_table_name_1_c, &exists_condition_c).await;
            let inspect_result_2 =
                exists_record(&inspect_table_name_2_c, &exists_condition_c).await;
            let inspect_result_3 =
                exists_record(&inspect_table_name_3_c, &exists_condition_c).await;
            let inspect_result_4 =
                exists_record(&inspect_table_name_4_c, &exists_condition_c).await;

            if inspect_result_1 == false
                && inspect_result_2 == false
                && inspect_result_3 == false
                && inspect_result_4 == false
            {
                let mut filtered_data_1st_lock = filtered_data_1st_arc_c.lock().await;

                filtered_data.symbol = symbol_c;

                filtered_data_1st_lock.push(filtered_data);
            }
        }));
    }
    try_join_all(task_vec).await?;

    // 2nd filtering: supertrend(ATR period 20, multiplier: 1.5, 30m close price), signal should be BUY
    let filtered_data_1st = filtered_data_1st_arc.lock().await.clone();
    let mut filtered_data_2nd: Vec<FilteredData> = Vec::new();
    let mut filtered_data_2nd_arc: Arc<Mutex<Vec<FilteredData>>> =
        Arc::new(Mutex::new(filtered_data_2nd));
    let mut task_vec = Vec::new();

    for element in filtered_data_1st {
        let mut rt_30m_vec: Vec<RealtimePriceData> = Vec::new();
        let mut supertrend_vec: Vec<SupertrendData> = Vec::new();
        let rt_price_30m_vec_c = alldata.rt_price_30m_vec.clone();
        let filtered_data_2nd_arc_c = Arc::clone(&filtered_data_2nd_arc);
        task_vec.push(tokio::spawn(async move {
            let rt_30m_option = rt_price_30m_vec_c
                .iter()
                .position(|x| *x.0 == element.symbol);
            let supertrend_option_30m =
                supertrend(&element.symbol, &rt_price_30m_vec_c, 20, 1.5, true).await;

            if rt_30m_option.is_some() && supertrend_option_30m.is_some() {
                rt_30m_vec = rt_price_30m_vec_c[rt_30m_option.unwrap()].1.clone();
                supertrend_vec = supertrend_option_30m.unwrap();
                let server_epoch = server_epoch().await;
                if rt_30m_vec.len() >= 3 && supertrend_vec.len() >= 3 && rt_30m_vec.last().unwrap().close_time > server_epoch {
                    let supertrend_search_result = supertrend_vec.binary_search_by_key(
                        &rt_30m_vec.last().unwrap().close_time,
                        |SupertrendData {
                             band_value,
                             signal,
                             area,
                             close_time,
                         }| *close_time,
                    );
                    if supertrend_search_result.is_ok() {
                        let current_price: Decimal = rust_decimal::prelude::FromPrimitive::from_f64(rt_30m_vec.last().unwrap().close_price).unwrap();

                        if supertrend_vec[supertrend_search_result.unwrap()].signal.as_ref().is_some_and(|x| x.contains("BUY"))
                            && current_price
                                < rust_decimal::prelude::FromPrimitive::from_f64(
                                    supertrend_vec[supertrend_search_result.unwrap()-1].band_value * 1.002,
                                )
                                .unwrap()
                            && supertrend_vec[supertrend_search_result.unwrap()-1].band_value > supertrend_vec[supertrend_search_result.unwrap()].band_value
                        {
                            let mut filtered_data_2nd_lock = filtered_data_2nd_arc_c.lock().await;
                            let mut filtered_data = FilteredData::new();
                            filtered_data.symbol = element.symbol.clone();
                            filtered_data.closetime = supertrend_vec[supertrend_search_result.unwrap()].close_time;
                            filtered_data.current_price = current_price;
                            filtered_data.stoploss = rust_decimal::prelude::FromPrimitive::from_f64(supertrend_vec[supertrend_search_result.unwrap()].band_value).unwrap();
                            let target_price = decimal_add(
                                filtered_data.current_price,
                                decimal_sub(filtered_data.current_price, filtered_data.stoploss),
                            );
                            filtered_data.target_price = target_price;

                            filtered_data_2nd_lock.push(filtered_data);
                        }
                    }
                }
            }
        }));
    }
    try_join_all(task_vec).await?;

    // 3rd filtering: ADX(10, 10) < 25.0
    let filtered_data_2nd = filtered_data_2nd_arc.lock().await.clone();
    let mut filtered_data_3rd: Vec<FilteredData> = Vec::new();
    let mut filtered_data_3rd_arc: Arc<Mutex<Vec<FilteredData>>> =
        Arc::new(Mutex::new(filtered_data_3rd));
    let mut task_vec = Vec::new();
    let valid_symbol_vec_c = alldata.valid_symbol_vec.clone();
    let adx_vec = adx(10, 10, &alldata.rt_price_30m_vec, &filtered_data_2nd).await?;
    for element in filtered_data_2nd {
        let mut adx_vec_c = adx_vec.clone();
        let symbol = element.symbol.clone();
        let close_time = element.closetime;
        let idx_result = adx_vec.iter().position(|elem| elem.0 == symbol);
        let filtered_data_3rd_arc_c = Arc::clone(&filtered_data_3rd_arc);
        if idx_result.is_some(){
            task_vec.push(tokio::spawn(async move {
                let closetime_idx_result = adx_vec_c[idx_result.unwrap()].1.iter().position(|elem| elem.close_time==close_time);
                if closetime_idx_result.is_some() {
                    if adx_vec_c[idx_result.unwrap()].1[closetime_idx_result.unwrap()].adx < 25.0 {
                        let mut filtered_3rd_symbols_lock =
                                    filtered_data_3rd_arc_c.lock().await;
                        let mut filtered_data = FilteredData::new();
                        filtered_data.symbol = element.symbol.clone();
                        filtered_data.closetime = element.closetime;
                        filtered_data.current_price = element.current_price;
                        filtered_data.stoploss = element.stoploss;
                        filtered_data.target_price = element.target_price;

                        filtered_3rd_symbols_lock.push(filtered_data);
                    }
                }
            }));
        }
    }
    try_join_all(task_vec).await?;

    // 4th filtering: MACD 1d (fast:3, slow:7, smoothing:3) MACD > signal
    let filtered_data_3rd = filtered_data_3rd_arc.lock().await.clone();
    let mut filtered_data_4th: Vec<FilteredData> = Vec::new();
    let mut filtered_data_4th_arc: Arc<Mutex<Vec<FilteredData>>> =
        Arc::new(Mutex::new(filtered_data_4th));
    let mut task_vec = Vec::new();
    let macd_vec = ema_macd(3, 7, 3, &alldata.rt_price_1d_vec, &filtered_data_3rd).await?;
    for element in filtered_data_3rd {
        let mut opclo_1d_vec: Vec<RealtimePriceData> = Vec::new();
        let mut supertrend_vec: Vec<SupertrendData> = Vec::new();
        let macd_vec_c = macd_vec.clone();
        let filtered_data_4th_arc_c = Arc::clone(&filtered_data_4th_arc);
        task_vec.push(tokio::spawn(async move {
            let search_result = macd_vec_c.iter().position(|x| x.0 == element.symbol);

            if search_result.is_some_and(|a| macd_vec_c[a].1.last().unwrap().macd_value > macd_vec_c[a].1.last().unwrap().signal_value) {
                let mut filtered_4th_symbols_lock =
                    filtered_data_4th_arc_c.lock().await;
                let mut filtered_data = FilteredData::new();
                filtered_data.symbol = element.symbol.clone();
                filtered_data.closetime = element.closetime;
                filtered_data.current_price = element.current_price;
                filtered_data.stoploss = element.stoploss;
                filtered_data.target_price = element.target_price;

                filtered_4th_symbols_lock.push(filtered_data);
            }
        }));
    }
    try_join_all(task_vec).await?;
    
    // 5th filtering: 0.5% <= the average amplitude of the latest 10 30m candles <= 1.0%
    let filtered_data_4th_c = filtered_data_4th_arc.lock().await.clone();
    let mut filtered_data_5th: Vec<FilteredData> = Vec::new();
    let mut filtered_data_5th_arc: Arc<Mutex<Vec<FilteredData>>> =
        Arc::new(Mutex::new(filtered_data_5th));
    let mut task_vec = Vec::new();
    for element in filtered_data_4th_c {
        let mut supertrend_vec: Vec<SupertrendData> = Vec::new();
        let rt_price_30m_vec_c = alldata.rt_price_30m_vec.clone();
        let filtered_data_5th_arc_c = Arc::clone(&filtered_data_5th_arc);

        task_vec.push(tokio::spawn(async move {
            let position_idx = rt_price_30m_vec_c.iter().position(|elem| elem.0 == element.symbol);
            
            if position_idx.is_some() {
                let vec_len = rt_price_30m_vec_c[position_idx.unwrap()].1.len();
                if vec_len >= 11 {
                    let candles = rt_price_30m_vec_c[position_idx.unwrap()].1.get(vec_len-12..vec_len-1).unwrap();
                    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 {
                        let mut filtered_data_5th_lock = filtered_data_5th_arc_c.lock().await;
                        let mut filtered_data = FilteredData::new();
                        filtered_data.symbol = element.symbol.clone();
                        filtered_data.closetime = element.closetime;
                        filtered_data.current_price = element.current_price;
                        filtered_data.stoploss = element.stoploss;
                        filtered_data.target_price = element.target_price;
                        
                        filtered_data_5th_lock.push(filtered_data);
                    }
                }
            }
        }));
    }
    try_join_all(task_vec).await?;

    let final_filtered_data = filtered_data_5th_arc.lock().await.clone();
    insert_pre_suggested_coins(5, false, &final_filtered_data, &alldata).await;

    Ok(())
}

pub async fn list_up_for_sell(
    all_data: &AllData,
    exchange_info_vec: &Vec<ExchangeInfo>,
    trade_fee_vec: &Vec<TradeFee>,
) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
    let filled_buy_orders = select_filled_buy_orders(5).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 = server_epoch().await;
        for element in filled_buy_orders {
            if element.used_usdt >= dec!(10.0) {
                let lot_step_size_option = exchange_info_vec
                    .iter()
                    .position(|exchange_info| exchange_info.symbol == element.symbol);
                let quote_commission_precision_option = exchange_info_vec
                    .iter()
                    .position(|exchange_info| exchange_info.symbol == element.symbol);

                let opclo_30m_option = all_data
                    .rt_price_30m_vec
                    .iter()
                    .position(|x| *x.0 == element.symbol);
                let supertrend_option_30m =
                    supertrend(&element.symbol, &all_data.rt_price_30m_vec, 20, 1.5, true).await;

                if lot_step_size_option.is_some()
                    && quote_commission_precision_option.is_some()
                    && opclo_30m_option.is_some()
                    && supertrend_option_30m.is_some()
                {
                    // update stoploss
                    supertrend_vec = supertrend_option_30m.unwrap();
                    let band_value: Decimal = rust_decimal::prelude::FromPrimitive::from_f64(supertrend_vec.last().unwrap().band_value).unwrap();
                    if supertrend_vec.last().unwrap().area.contains("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_vec[lot_step_size_option.unwrap()].stepsize;
                    let quote_commission_precision = exchange_info_vec
                        [quote_commission_precision_option.unwrap()]
                    .quote_commission_precision;
                    let base_qty_to_be_ordered =
                        element.base_qty_ordered.round_dp_with_strategy(
                            lot_step_size.normalize().scale(),
                            RoundingStrategy::ToZero,
                        );

                    if (element.is_long == 0 || element.is_long == 1)
                        && !element.current_price.is_zero()
                    {
                        if element.current_price >= element.target_price
                            && element.pure_profit_percent >= 0.1
                        {
                            limit_order_sell(
                                &element,
                                element.current_price,
                                base_qty_to_be_ordered,
                                &client,
                                &exchange_info_vec,
                                &trade_fee_vec,
                            )
                            .await;
                        } else if element.current_price <= element.stoploss {
                            limit_order_sell(
                                &element,
                                element.current_price,
                                base_qty_to_be_ordered,
                                &client,
                                &exchange_info_vec,
                                &trade_fee_vec,
                            )
                            .await;
                        } else if server_epoch - element.transact_time > (1_800_000) * 10 && element.pure_profit_percent.is_sign_positive() {
                            limit_order_sell(
                                &element,
                                element.current_price,
                                base_qty_to_be_ordered,
                                &client,
                                &exchange_info_vec,
                                &trade_fee_vec,
                            )
                            .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(())
}
