/* TA-LIB Copyright (c) 1999-2025, Mario Fortier
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or
 * without modification, are permitted provided that the following
 * conditions are met:
 *
 * - Redistributions of source code must retain the above copyright
 *   notice, this list of conditions and the following disclaimer.
 *
 * - Redistributions in binary form must reproduce the above copyright
 *   notice, this list of conditions and the following disclaimer in
 *   the documentation and/or other materials provided with the
 *   distribution.
 *
 * - Neither name of author nor the names of its contributors
 *   may be used to endorse or promote products derived from this
 *   software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
 * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
 * REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
 * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
 * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
 * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

/* Important:
 *  This file is automatically generated by the utility ta_codegen.
 *  Any modifications will be lost on next execution of ta_codegen.
 *
 *  Modifications should instead be done with the "C" source file
 *  in ta-lib\src\ta_func
 */

/* List of contributors:
 *
 *  Initial  Name/description
 *  -------------------------------------------------------------------
 *  MF       Mario Fortier
 *  BT       BobTrader (TADoc.org forum user).
 *
 * Change history:
 *
 *  MMDDYY BY   Description
 *  -------------------------------------------------------------------
 *  120802 MF    Template creation.
 *  052603 MF    Adapt code to compile with .NET Managed C++
 *  062704 MF    Prevent divide by zero.
 *  121705 MF    Java port related changes.
 *  060907 MF,BT Fix #1727704. MFI logic bug when no price movement
 */

// Import types from parent module
use super::*;

// Allow non-snake-case names to maintain TA-Lib API compatibility
#[allow(non_snake_case)]
#[allow(unused_variables)]
#[allow(dead_code)]
#[allow(unused_mut)]
#[allow(unused_assignments)]
impl Core {
    /// Lookback period for [`Core::mfi`]: the number of leading input values consumed before the
    /// first output value can be produced.
    ///
    /// # Arguments
    ///
    /// * `optInTimePeriod` — Lookback window for summing money flow (default 14, range
    ///   2..=100000)
    ///
    /// Returns `usize::MAX` when a parameter is out of range. Integer parameters accept `i32::MIN`
    /// to select their default value.
    #[inline]
    pub fn mfi_lookback(&self, mut optInTimePeriod: i32) -> usize {
        if ((optInTimePeriod) as i32) == (i32::MIN) {
            optInTimePeriod = 14;
        } else if (((optInTimePeriod) as i32) < 2) || (((optInTimePeriod) as i32) > 100000) {
            return usize::MAX;
        }
        return (optInTimePeriod + self.unstable_period[FuncUnstId::Mfi as usize]) as usize;
    }
    /// Money Flow Index: a volume-weighted momentum oscillator (0-100) comparing positive vs
    /// negative money flow over a period. A volume-based analog of RSI. >80 overbought, \<20
    /// oversold.
    ///
    /// # Formula
    ///
    /// ```text
    /// TP = (High+Low+Close)/3; MF = TP*Volume, classed positive if TP>prevTP, negative if TP<prevTP, neither if equal. MFI = 100 * posSumMF/(posSumMF+negSumMF).
    /// ```
    ///
    /// # Notes
    ///
    /// * When the typical price is unchanged from the prior bar, that bar's money flow is counted
    ///   as neither positive nor negative.
    ///
    /// # Arguments
    ///
    /// * `startIdx` — Start index of the requested calculation range.
    /// * `endIdx` — End index of the requested calculation range (inclusive).
    /// * `inHigh` — High prices per bar.
    /// * `inLow` — Low prices per bar.
    /// * `inClose` — Close prices per bar.
    /// * `inVolume` — Volume per bar.
    /// * `optInTimePeriod` — Lookback window for summing money flow (default 14, range
    ///   2..=100000)
    /// * `outBegIdx` — Set to the input index of the first output value.
    /// * `outNBElement` — Set to the number of output values written.
    /// * `outReal` — Money Flow Index.
    ///
    /// Integer parameters accept `i32::MIN` to select their default value.
    ///
    /// # Errors
    ///
    /// Returns [`RetCode::OutOfRangeStartIndex`] when `endIdx < startIdx`, and
    /// [`RetCode::BadParam`] when an optional parameter is outside its documented range.
    ///
    /// # Panics
    ///
    /// Input slices must cover `startIdx..=endIdx` and output slices must hold the number of values
    /// produced for that range: undersized slices panic or, for functions that forward to unchecked
    /// internals, cause undefined behavior. Sizing every output slice to the input length is always
    /// sufficient.
    ///
    /// # Examples
    ///
    /// ```
    /// use ta_lib::{Core, RetCode};
    ///
    /// let high: Vec<f64> = (0..252).map(|i| 101.0 + 10.0 * (0.1 * i as f64).sin()).collect();
    /// let low: Vec<f64> = (0..252).map(|i| 99.0 + 10.0 * (0.1 * i as f64).sin()).collect();
    /// let close: Vec<f64> = (0..252).map(|i| 100.0 + 10.0 * (0.1 * i as f64).sin()).collect();
    /// let volume: Vec<f64> = (0..252).map(|i| 10_000.0 + 100.0 * i as f64).collect();
    ///
    /// let core = Core::new();
    /// let mut out_beg = 0;
    /// let mut out_nb = 0;
    /// let mut out = vec![0.0; 252];
    ///
    /// let ret = core.mfi(
    ///     0, high.len() - 1, &high, &low, &close, &volume, 14,
    ///     &mut out_beg, &mut out_nb, &mut out,
    /// );
    /// assert_eq!(ret, RetCode::Success);
    /// assert!(out_nb > 0);
    /// ```
    ///
    /// # See also
    ///
    /// [`Core::rsi`] · [`Core::ad`] · [`Core::adosc`]
    ///
    /// Further reading: [ta-lib.org/functions/mfi](https://ta-lib.org/functions/mfi/)
    #[doc(alias = "MoneyFlowIndex")]
    pub fn mfi(
        &self,
        startIdx: usize,
        endIdx: usize,
        inHigh: &[f64],
        inLow: &[f64],
        inClose: &[f64],
        inVolume: &[f64],
        mut optInTimePeriod: i32,
        outBegIdx: &mut usize,
        outNBElement: &mut usize,
        outReal: &mut [f64],
    ) -> RetCode {
        if endIdx < startIdx {
            return RetCode::OutOfRangeStartIndex;
        }
        if ((optInTimePeriod) as i32) == (i32::MIN) {
            optInTimePeriod = 14;
        } else if (((optInTimePeriod) as i32) < 2) || (((optInTimePeriod) as i32) > 100000) {
            return RetCode::BadParam;
        }
        let mut startIdx = startIdx;
        let mut posSumMF: f64 = 0.0_f64;
        let mut negSumMF: f64 = 0.0_f64;
        let mut prevValue: f64 = 0.0_f64;
        let mut tempValue1: f64 = 0.0_f64;
        let mut tempValue2: f64 = 0.0_f64;
        let mut lookbackTotal: usize = 0_usize;
        let mut outIdx: usize = 0_usize;
        let mut i: usize = 0_usize;
        let mut today: usize = 0_usize;
        let mut mflow_positive: Vec<f64> = Vec::new();
        let mut mflow_negative: Vec<f64> = Vec::new();
        let mut mflow_Idx: usize = 0;
        let mut maxIdx_mflow: usize = 49;
        // Id, Type, Static Size
        if optInTimePeriod < 1 { return RetCode::AllocErr; }
        mflow_positive = vec![0.0_f64; (optInTimePeriod) as usize];
        mflow_negative = vec![0.0_f64; (optInTimePeriod) as usize];
        maxIdx_mflow = ((optInTimePeriod) as usize) - 1;
        mflow_Idx = 0;
        (*outBegIdx) = 0;
        (*outNBElement) = 0;
        // Adjust startIdx to account for the lookback period.
        lookbackTotal = (optInTimePeriod + self.unstable_period[FuncUnstId::Mfi as usize]) as usize;
        if startIdx < lookbackTotal {
            startIdx = lookbackTotal;
        }
        // Make sure there is still something to evaluate.
        if startIdx > endIdx {
            return RetCode::Success;
        }
        outIdx = 0;
        // Index into the output.
        // Accumulate the positive and negative money flow
        // among the initial period.
        today = startIdx - lookbackTotal;
        prevValue = (inHigh[today] + inLow[today] + inClose[today]) / 3.0;
        posSumMF = 0.0;
        negSumMF = 0.0;
        today += 1;
        // for( i = (optInTimePeriod) as usize; i > 0; i -= 1 )
        i = (optInTimePeriod) as usize;
        while i > 0 {
            tempValue1 = (inHigh[today] + inLow[today] + inClose[today]) / 3.0;
            tempValue2 = tempValue1 - prevValue;
            prevValue = tempValue1;
            tempValue1 *= inVolume[{ let _v = today; today += 1; _v }];
            if tempValue2 < 0_f64 {
                mflow_negative[mflow_Idx] = tempValue1;
                negSumMF += tempValue1;
                mflow_positive[mflow_Idx] = 0.0;
            } else if tempValue2 > 0_f64 {
                mflow_positive[mflow_Idx] = tempValue1;
                posSumMF += tempValue1;
                mflow_negative[mflow_Idx] = 0.0;
            } else {
                mflow_positive[mflow_Idx] = 0.0;
                mflow_negative[mflow_Idx] = 0.0;
            }
            mflow_Idx += 1;
            if mflow_Idx > maxIdx_mflow { mflow_Idx = 0; }
            i -= 1;
        }
        // The following two equations are equivalent:
        //    MFI = 100 - (100 / 1 + (posSumMF/negSumMF))
        //    MFI = 100 * (posSumMF/(posSumMF+negSumMF))
        // The second equation is used here for speed optimization.
        if today > startIdx {
            tempValue1 = posSumMF + negSumMF;
            if tempValue1 < 1.0 {
                outReal[outIdx] = 0.0;
                outIdx += 1;
            } else {
                outReal[outIdx] = 100.0 * (posSumMF / tempValue1);
                outIdx += 1;
            }
        } else {
            // Skip the unstable period. Do the processing
            // but do not write it in the output.
            while today < startIdx {
                posSumMF -= mflow_positive[mflow_Idx];
                negSumMF -= mflow_negative[mflow_Idx];
                tempValue1 = (inHigh[today] + inLow[today] + inClose[today]) / 3.0;
                tempValue2 = tempValue1 - prevValue;
                prevValue = tempValue1;
                tempValue1 *= inVolume[{ let _v = today; today += 1; _v }];
                if tempValue2 < 0_f64 {
                    mflow_negative[mflow_Idx] = tempValue1;
                    negSumMF += tempValue1;
                    mflow_positive[mflow_Idx] = 0.0;
                } else if tempValue2 > 0_f64 {
                    mflow_positive[mflow_Idx] = tempValue1;
                    posSumMF += tempValue1;
                    mflow_negative[mflow_Idx] = 0.0;
                } else {
                    mflow_positive[mflow_Idx] = 0.0;
                    mflow_negative[mflow_Idx] = 0.0;
                }
                mflow_Idx += 1;
                if mflow_Idx > maxIdx_mflow { mflow_Idx = 0; }
            }
        }
        // Unstable period skipped... now continue
        // processing if needed.
        while today <= endIdx {
            posSumMF -= mflow_positive[mflow_Idx];
            negSumMF -= mflow_negative[mflow_Idx];
            tempValue1 = (inHigh[today] + inLow[today] + inClose[today]) / 3.0;
            tempValue2 = tempValue1 - prevValue;
            prevValue = tempValue1;
            tempValue1 *= inVolume[{ let _v = today; today += 1; _v }];
            if tempValue2 < 0_f64 {
                mflow_negative[mflow_Idx] = tempValue1;
                negSumMF += tempValue1;
                mflow_positive[mflow_Idx] = 0.0;
            } else if tempValue2 > 0_f64 {
                mflow_positive[mflow_Idx] = tempValue1;
                posSumMF += tempValue1;
                mflow_negative[mflow_Idx] = 0.0;
            } else {
                mflow_positive[mflow_Idx] = 0.0;
                mflow_negative[mflow_Idx] = 0.0;
            }
            tempValue1 = posSumMF + negSumMF;
            if tempValue1 < 1.0 {
                outReal[outIdx] = 0.0;
                outIdx += 1;
            } else {
                outReal[outIdx] = 100.0 * (posSumMF / tempValue1);
                outIdx += 1;
            }
            mflow_Idx += 1;
            if mflow_Idx > maxIdx_mflow { mflow_Idx = 0; }
        }
        (*outBegIdx) = startIdx;
        (*outNBElement) = outIdx;
        return RetCode::Success;
    }
    /// Unchecked variant of [`Core::mfi`], used for internal cross-indicator calls.
    ///
    /// Skips parameter validation and uses unchecked indexing internally. Every argument must
    /// satisfy the constraints documented on [`Core::mfi`]; an out-of-range parameter, an input
    /// slice not covering `startIdx..=endIdx`, or an undersized output slice may panic or cause
    /// undefined behavior. Prefer [`Core::mfi`].
    #[inline]
    pub fn mfi_unguarded(
        &self,
        mut startIdx: usize,
        endIdx: usize,
        inHigh: &[f64],
        inLow: &[f64],
        inClose: &[f64],
        inVolume: &[f64],
        mut optInTimePeriod: i32,
        outBegIdx: &mut usize,
        outNBElement: &mut usize,
        outReal: &mut [f64],
    ) -> RetCode {
        let mut posSumMF: f64 = 0.0_f64;
        let mut negSumMF: f64 = 0.0_f64;
        let mut prevValue: f64 = 0.0_f64;
        let mut tempValue1: f64 = 0.0_f64;
        let mut tempValue2: f64 = 0.0_f64;
        let mut lookbackTotal: usize = 0_usize;
        let mut outIdx: usize = 0_usize;
        let mut i: usize = 0_usize;
        let mut today: usize = 0_usize;
        let mut mflow_positive: Vec<f64> = Vec::new();
        let mut mflow_negative: Vec<f64> = Vec::new();
        let mut mflow_Idx: usize = 0;
        let mut maxIdx_mflow: usize = 49;
        unsafe {
        assert!(endIdx < inHigh.len());
        assert!(endIdx < inLow.len());
        assert!(endIdx < inClose.len());
        assert!(endIdx < inVolume.len());
        let _assertLb = self.mfi_lookback(optInTimePeriod);
        let _assertStart = if startIdx > _assertLb { startIdx } else { _assertLb };
        assert!(_assertStart > endIdx || endIdx - _assertStart < outReal.len());
        if optInTimePeriod < 1 { return RetCode::AllocErr; }
        mflow_positive = vec![0.0_f64; (optInTimePeriod) as usize];
        mflow_negative = vec![0.0_f64; (optInTimePeriod) as usize];
        maxIdx_mflow = ((optInTimePeriod) as usize) - 1;
        mflow_Idx = 0;
        (*outBegIdx) = 0;
        (*outNBElement) = 0;
        lookbackTotal = (optInTimePeriod + self.unstable_period[FuncUnstId::Mfi as usize]) as usize;
        if startIdx < lookbackTotal {
            startIdx = lookbackTotal;
        }
        if startIdx > endIdx {
            return RetCode::Success;
        }
        outIdx = 0;
        today = startIdx - lookbackTotal;
        prevValue = (*inHigh.as_ptr().add(today) + *inLow.as_ptr().add(today) + *inClose.as_ptr().add(today)) / 3.0;
        posSumMF = 0.0;
        negSumMF = 0.0;
        today += 1;
        // for( i = (optInTimePeriod) as usize; i > 0; i -= 1 )
        i = (optInTimePeriod) as usize;
        while i > 0 {
            tempValue1 = (*inHigh.as_ptr().add(today) + *inLow.as_ptr().add(today) + *inClose.as_ptr().add(today)) / 3.0;
            tempValue2 = tempValue1 - prevValue;
            prevValue = tempValue1;
            tempValue1 *= *inVolume.as_ptr().add({ let _v = today; today += 1; _v });
            if tempValue2 < 0_f64 {
                *mflow_negative.as_mut_ptr().add(mflow_Idx) = tempValue1;
                negSumMF += tempValue1;
                *mflow_positive.as_mut_ptr().add(mflow_Idx) = 0.0;
            } else if tempValue2 > 0_f64 {
                *mflow_positive.as_mut_ptr().add(mflow_Idx) = tempValue1;
                posSumMF += tempValue1;
                *mflow_negative.as_mut_ptr().add(mflow_Idx) = 0.0;
            } else {
                *mflow_positive.as_mut_ptr().add(mflow_Idx) = 0.0;
                *mflow_negative.as_mut_ptr().add(mflow_Idx) = 0.0;
            }
            mflow_Idx += 1;
            if mflow_Idx > maxIdx_mflow { mflow_Idx = 0; }
            i -= 1;
        }
        if today > startIdx {
            tempValue1 = posSumMF + negSumMF;
            if tempValue1 < 1.0 {
                *outReal.as_mut_ptr().add(outIdx) = 0.0;
                outIdx += 1;
            } else {
                *outReal.as_mut_ptr().add(outIdx) = 100.0 * (posSumMF / tempValue1);
                outIdx += 1;
            }
        } else {
            while today < startIdx {
                posSumMF -= *mflow_positive.as_ptr().add(mflow_Idx);
                negSumMF -= *mflow_negative.as_ptr().add(mflow_Idx);
                tempValue1 = (*inHigh.as_ptr().add(today) + *inLow.as_ptr().add(today) + *inClose.as_ptr().add(today)) / 3.0;
                tempValue2 = tempValue1 - prevValue;
                prevValue = tempValue1;
                tempValue1 *= *inVolume.as_ptr().add({ let _v = today; today += 1; _v });
                if tempValue2 < 0_f64 {
                    *mflow_negative.as_mut_ptr().add(mflow_Idx) = tempValue1;
                    negSumMF += tempValue1;
                    *mflow_positive.as_mut_ptr().add(mflow_Idx) = 0.0;
                } else if tempValue2 > 0_f64 {
                    *mflow_positive.as_mut_ptr().add(mflow_Idx) = tempValue1;
                    posSumMF += tempValue1;
                    *mflow_negative.as_mut_ptr().add(mflow_Idx) = 0.0;
                } else {
                    *mflow_positive.as_mut_ptr().add(mflow_Idx) = 0.0;
                    *mflow_negative.as_mut_ptr().add(mflow_Idx) = 0.0;
                }
                mflow_Idx += 1;
                if mflow_Idx > maxIdx_mflow { mflow_Idx = 0; }
            }
        }
        while today <= endIdx {
            posSumMF -= *mflow_positive.as_ptr().add(mflow_Idx);
            negSumMF -= *mflow_negative.as_ptr().add(mflow_Idx);
            tempValue1 = (*inHigh.as_ptr().add(today) + *inLow.as_ptr().add(today) + *inClose.as_ptr().add(today)) / 3.0;
            tempValue2 = tempValue1 - prevValue;
            prevValue = tempValue1;
            tempValue1 *= *inVolume.as_ptr().add({ let _v = today; today += 1; _v });
            if tempValue2 < 0_f64 {
                *mflow_negative.as_mut_ptr().add(mflow_Idx) = tempValue1;
                negSumMF += tempValue1;
                *mflow_positive.as_mut_ptr().add(mflow_Idx) = 0.0;
            } else if tempValue2 > 0_f64 {
                *mflow_positive.as_mut_ptr().add(mflow_Idx) = tempValue1;
                posSumMF += tempValue1;
                *mflow_negative.as_mut_ptr().add(mflow_Idx) = 0.0;
            } else {
                *mflow_positive.as_mut_ptr().add(mflow_Idx) = 0.0;
                *mflow_negative.as_mut_ptr().add(mflow_Idx) = 0.0;
            }
            tempValue1 = posSumMF + negSumMF;
            if tempValue1 < 1.0 {
                *outReal.as_mut_ptr().add(outIdx) = 0.0;
                outIdx += 1;
            } else {
                *outReal.as_mut_ptr().add(outIdx) = 100.0 * (posSumMF / tempValue1);
                outIdx += 1;
            }
            mflow_Idx += 1;
            if mflow_Idx > maxIdx_mflow { mflow_Idx = 0; }
        }
        (*outBegIdx) = startIdx;
        (*outNBElement) = outIdx;
        return RetCode::Success;
        } // unsafe
    }
}
/***************/
/* End of File */
/***************/
