/* 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
 *
 *
 * Change history:
 *
 *  MMDDYY BY   Description
 *  -------------------------------------------------------------------
 *  010802 MF   Template creation.
 *  052603 MF   Adapt code to compile with .NET Managed C++
 */

// 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::macdext`]: the number of leading input values consumed before
    /// the first output value can be produced.
    ///
    /// # Arguments
    ///
    /// * `optInFastPeriod` — Period of the fast MA (default 12, range 2..=100000)
    /// * `optInFastMAType` — MA type for the fast MA (default 0 = SMA, values: 0=SMA, 1=EMA,
    ///   2=WMA, 3=DEMA, 4=TEMA, 5=TRIMA, 6=KAMA, 7=MAMA, 8=T3)
    /// * `optInSlowPeriod` — Period of the slow MA (default 26, range 2..=100000)
    /// * `optInSlowMAType` — MA type for the slow MA (default 0 = SMA, values: 0=SMA, 1=EMA,
    ///   2=WMA, 3=DEMA, 4=TEMA, 5=TRIMA, 6=KAMA, 7=MAMA, 8=T3)
    /// * `optInSignalPeriod` — Period of the signal-line MA (default 9, range 1..=100000)
    /// * `optInSignalMAType` — MA type for the signal line (default 0 = SMA, values: 0=SMA,
    ///   1=EMA, 2=WMA, 3=DEMA, 4=TEMA, 5=TRIMA, 6=KAMA, 7=MAMA, 8=T3)
    ///
    /// Returns `usize::MAX` when a parameter is out of range. Integer parameters accept `i32::MIN`
    /// to select their default value.
    #[inline]
    pub fn macdext_lookback(&self, mut optInFastPeriod: i32, mut optInFastMAType: i32, mut optInSlowPeriod: i32, mut optInSlowMAType: i32, mut optInSignalPeriod: i32, mut optInSignalMAType: i32) -> usize {
        if ((optInFastPeriod) as i32) == (i32::MIN) {
            optInFastPeriod = 12;
        } else if (((optInFastPeriod) as i32) < 2) || (((optInFastPeriod) as i32) > 100000) {
            return usize::MAX;
        }
        if ((optInSlowPeriod) as i32) == (i32::MIN) {
            optInSlowPeriod = 26;
        } else if (((optInSlowPeriod) as i32) < 2) || (((optInSlowPeriod) as i32) > 100000) {
            return usize::MAX;
        }
        if ((optInSignalPeriod) as i32) == (i32::MIN) {
            optInSignalPeriod = 9;
        } else if (((optInSignalPeriod) as i32) < 1) || (((optInSignalPeriod) as i32) > 100000) {
            return usize::MAX;
        }
        let mut tempInteger: usize = 0_usize;
        let mut lookbackLargest: usize = 0_usize;
        // Find the MA with the largest lookback
        lookbackLargest = self.ma_lookback(optInFastPeriod, optInFastMAType);
        tempInteger = self.ma_lookback(optInSlowPeriod, optInSlowMAType);
        if tempInteger > lookbackLargest {
            lookbackLargest = tempInteger;
        }
        // Add to the largest MA lookback the signal line lookback
        return (lookbackLargest + self.ma_lookback(optInSignalPeriod, optInSignalMAType)) as usize;
    }
    /// MACD variant where the fast, slow, and signal moving averages each use a user-selectable MA
    /// type. Outputs the MACD line, its signal line, and their difference (histogram). Hist sign
    /// change (MACD crossing its signal line) flags momentum shifts.
    ///
    /// # Formula
    ///
    /// ```text
    /// MACD = MA_fast(inReal) - MA_slow(inReal)
    /// Signal = MA_signal(MACD)
    /// Hist = MACD - Signal
    /// (each MA_* uses its own MA type and period)
    /// ```
    ///
    /// # Notes
    ///
    /// * If the slow period is set smaller than the fast period, the fast and slow periods and
    ///   their MA types are swapped so the slow moving average is always the longer one.
    /// * A signal period of 1 disables signal-line smoothing for every signal MAType: the signal
    ///   equals the MACD line and the histogram is zero.
    ///
    /// # Arguments
    ///
    /// * `startIdx` — Start index of the requested calculation range.
    /// * `endIdx` — End index of the requested calculation range (inclusive).
    /// * `inReal` — Source series.
    /// * `optInFastPeriod` — Period of the fast MA (default 12, range 2..=100000)
    /// * `optInFastMAType` — MA type for the fast MA (default 0 = SMA, values: 0=SMA, 1=EMA,
    ///   2=WMA, 3=DEMA, 4=TEMA, 5=TRIMA, 6=KAMA, 7=MAMA, 8=T3)
    /// * `optInSlowPeriod` — Period of the slow MA (default 26, range 2..=100000)
    /// * `optInSlowMAType` — MA type for the slow MA (default 0 = SMA, values: 0=SMA, 1=EMA,
    ///   2=WMA, 3=DEMA, 4=TEMA, 5=TRIMA, 6=KAMA, 7=MAMA, 8=T3)
    /// * `optInSignalPeriod` — Period of the signal-line MA (default 9, range 1..=100000)
    /// * `optInSignalMAType` — MA type for the signal line (default 0 = SMA, values: 0=SMA,
    ///   1=EMA, 2=WMA, 3=DEMA, 4=TEMA, 5=TRIMA, 6=KAMA, 7=MAMA, 8=T3)
    /// * `outBegIdx` — Set to the input index of the first output value.
    /// * `outNBElement` — Set to the number of output values written.
    /// * `outMACD` — MACD line: fast MA minus slow MA.
    /// * `outMACDSignal` — Signal line: MA of the MACD line.
    /// * `outMACDHist` — Histogram: MACD minus signal.
    ///
    /// 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 data: Vec<f64> = (0..252).map(|i| 100.0 + 10.0 * (0.1 * i as f64).sin()).collect();
    ///
    /// let core = Core::new();
    /// let mut out_beg = 0;
    /// let mut out_nb = 0;
    /// let mut macd = vec![0.0; 252];
    /// let mut macd_signal = vec![0.0; 252];
    /// let mut macd_hist = vec![0.0; 252];
    ///
    /// let ret = core.macdext(
    ///     0, data.len() - 1, &data, 12, 0, 26, 0, 9, 0,
    ///     &mut out_beg, &mut out_nb, &mut macd, &mut macd_signal, &mut macd_hist,
    /// );
    /// assert_eq!(ret, RetCode::Success);
    /// assert!(out_nb > 0);
    /// ```
    ///
    /// # See also
    ///
    /// [`Core::macd`] · [`Core::macdfix`] · [`Core::ma`] · [`Core::ema`] · [`Core::apo`] ·
    /// [`Core::ppo`]
    ///
    /// Further reading: [ta-lib.org/functions/macdext](https://ta-lib.org/functions/macdext/)
    #[doc(alias = "MACDExtended")]
    #[doc(alias = "MACDwithcontrollableMAtype")]
    pub fn macdext(
        &self,
        startIdx: usize,
        endIdx: usize,
        inReal: &[f64],
        mut optInFastPeriod: i32,
        mut optInFastMAType: i32,
        mut optInSlowPeriod: i32,
        mut optInSlowMAType: i32,
        mut optInSignalPeriod: i32,
        mut optInSignalMAType: i32,
        outBegIdx: &mut usize,
        outNBElement: &mut usize,
        outMACD: &mut [f64],
        outMACDSignal: &mut [f64],
        outMACDHist: &mut [f64],
    ) -> RetCode {
        if endIdx < startIdx {
            return RetCode::OutOfRangeStartIndex;
        }
        if ((optInFastPeriod) as i32) == (i32::MIN) {
            optInFastPeriod = 12;
        } else if (((optInFastPeriod) as i32) < 2) || (((optInFastPeriod) as i32) > 100000) {
            return RetCode::BadParam;
        }
        if ((optInSlowPeriod) as i32) == (i32::MIN) {
            optInSlowPeriod = 26;
        } else if (((optInSlowPeriod) as i32) < 2) || (((optInSlowPeriod) as i32) > 100000) {
            return RetCode::BadParam;
        }
        if ((optInSignalPeriod) as i32) == (i32::MIN) {
            optInSignalPeriod = 9;
        } else if (((optInSignalPeriod) as i32) < 1) || (((optInSignalPeriod) as i32) > 100000) {
            return RetCode::BadParam;
        }
        let mut startIdx = startIdx;
        let mut slowMABuffer: Vec<f64> = Vec::new();
        let mut fastMABuffer: Vec<f64> = Vec::new();
        let mut retCode: RetCode = RetCode::Success;
        let mut tempInteger: usize = 0_usize;
        let mut outBegIdx1: usize = 0_usize;
        let mut outNbElement1: usize = 0_usize;
        let mut outBegIdx2: usize = 0_usize;
        let mut outNbElement2: usize = 0_usize;
        let mut lookbackTotal: usize = 0_usize;
        let mut lookbackSignal: usize = 0_usize;
        let mut lookbackLargest: usize = 0_usize;
        let mut i: usize = 0_usize;
        let mut tempMAType: usize = 0_usize;
        // Make sure slow is really slower than
        // the fast period! if not, swap...
        if optInSlowPeriod < optInFastPeriod {
            // swap period
            tempInteger = (optInSlowPeriod) as usize;
            optInSlowPeriod = optInFastPeriod;
            optInFastPeriod = (tempInteger) as i32;
            // swap type
            tempMAType = (optInSlowMAType) as usize;
            optInSlowMAType = optInFastMAType;
            optInFastMAType = (tempMAType) as i32;
        }
        // Find the MA with the largest lookback
        lookbackLargest = self.ma_lookback(optInFastPeriod, optInFastMAType);
        tempInteger = self.ma_lookback(optInSlowPeriod, optInSlowMAType);
        if tempInteger > lookbackLargest {
            lookbackLargest = tempInteger;
        }
        // Add the lookback needed for the signal line
        lookbackSignal = self.ma_lookback(optInSignalPeriod, optInSignalMAType);
        lookbackTotal = lookbackSignal + lookbackLargest;
        // Move up the start index if there is not
        // enough initial data.
        if startIdx < lookbackTotal {
            startIdx = lookbackTotal;
        }
        // Make sure there is still something to evaluate.
        if startIdx > endIdx {
            (*outBegIdx) = 0;
            (*outNBElement) = 0;
            return RetCode::Success;
        }
        // Allocate intermediate buffer for fast/slow MA.
        tempInteger = endIdx - startIdx + 1 + lookbackSignal;
        fastMABuffer = vec![0.0_f64; (tempInteger * 1) as usize];
        slowMABuffer = vec![0.0_f64; (tempInteger * 1) as usize];
        // Calculate the slow MA.
        //
        // Move back the startIdx to get enough data
        // for the signal period. That way, once the
        // signal calculation is done, all the output
        // will start at the requested 'startIdx'.
        tempInteger = startIdx - lookbackSignal;
        retCode = self.ma_unguarded(tempInteger, endIdx, inReal, optInSlowPeriod, optInSlowMAType, &mut outBegIdx1, &mut outNbElement1, &mut slowMABuffer[..]);
        if retCode != RetCode::Success {
            (*outBegIdx) = 0;
            (*outNBElement) = 0;
            return retCode;
        }
        // Calculate the fast MA.
        retCode = self.ma_unguarded(tempInteger, endIdx, inReal, optInFastPeriod, optInFastMAType, &mut outBegIdx2, &mut outNbElement2, &mut fastMABuffer[..]);
        if retCode != RetCode::Success {
            (*outBegIdx) = 0;
            (*outNBElement) = 0;
            return retCode;
        }
        // Parano tests. Will be removed eventually.
        if outBegIdx1 != tempInteger || outBegIdx2 != tempInteger || outNbElement1 != outNbElement2 || outNbElement1 != endIdx - startIdx + 1 + lookbackSignal {
            (*outBegIdx) = 0;
            (*outNBElement) = 0;
            return RetCode::BadParam;
        }
        // Calculate (fast MA) - (slow MA).
        // for( i = 0; i < outNbElement1; i += 1 )
        i = 0;
        while i < outNbElement1 {
            fastMABuffer[i] = fastMABuffer[i] - slowMABuffer[i];
            i += 1;
        }
        // Copy the result into the output for the caller.
        {
            let _n = ((endIdx - startIdx + 1) * 1) as usize;
            let _di = (0) as usize;
            let _si = (lookbackSignal) as usize;
            outMACD[_di.._di + _n].copy_from_slice(&fastMABuffer[_si.._si + _n]);
        };
        // Calculate the signal/trigger line.
        retCode = self.ma_unguarded(0, outNbElement1 - 1, &fastMABuffer, optInSignalPeriod, optInSignalMAType, &mut outBegIdx2, &mut outNbElement2, outMACDSignal);
        if retCode != RetCode::Success {
            (*outBegIdx) = 0;
            (*outNBElement) = 0;
            return retCode;
        }
        // Calculate the histogram.
        // for( i = 0; i < outNbElement2; i += 1 )
        i = 0;
        while i < outNbElement2 {
            outMACDHist[i] = ((outMACD[i] - outMACDSignal[i]) as f64);
            i += 1;
        }
        // All done! Indicate the output limits and return success.
        (*outBegIdx) = startIdx;
        (*outNBElement) = outNbElement2;
        return RetCode::Success;
    }
    /// Unchecked variant of [`Core::macdext`], used for internal cross-indicator calls.
    ///
    /// Skips parameter validation and uses unchecked indexing internally. Every argument must
    /// satisfy the constraints documented on [`Core::macdext`]; 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::macdext`].
    #[inline]
    pub fn macdext_unguarded(
        &self,
        mut startIdx: usize,
        endIdx: usize,
        inReal: &[f64],
        mut optInFastPeriod: i32,
        mut optInFastMAType: i32,
        mut optInSlowPeriod: i32,
        mut optInSlowMAType: i32,
        mut optInSignalPeriod: i32,
        mut optInSignalMAType: i32,
        outBegIdx: &mut usize,
        outNBElement: &mut usize,
        outMACD: &mut [f64],
        outMACDSignal: &mut [f64],
        outMACDHist: &mut [f64],
    ) -> RetCode {
        let mut slowMABuffer: Vec<f64> = Vec::new();
        let mut fastMABuffer: Vec<f64> = Vec::new();
        let mut retCode: RetCode = RetCode::Success;
        let mut tempInteger: usize = 0_usize;
        let mut outBegIdx1: usize = 0_usize;
        let mut outNbElement1: usize = 0_usize;
        let mut outBegIdx2: usize = 0_usize;
        let mut outNbElement2: usize = 0_usize;
        let mut lookbackTotal: usize = 0_usize;
        let mut lookbackSignal: usize = 0_usize;
        let mut lookbackLargest: usize = 0_usize;
        let mut i: usize = 0_usize;
        let mut tempMAType: usize = 0_usize;
        unsafe {
        assert!(endIdx < inReal.len());
        let _assertLb = self.macdext_lookback(optInFastPeriod, optInFastMAType, optInSlowPeriod, optInSlowMAType, optInSignalPeriod, optInSignalMAType);
        let _assertStart = if startIdx > _assertLb { startIdx } else { _assertLb };
        assert!(_assertStart > endIdx || endIdx - _assertStart < outMACD.len());
        assert!(_assertStart > endIdx || endIdx - _assertStart < outMACDSignal.len());
        assert!(_assertStart > endIdx || endIdx - _assertStart < outMACDHist.len());
        if optInSlowPeriod < optInFastPeriod {
            tempInteger = (optInSlowPeriod) as usize;
            optInSlowPeriod = optInFastPeriod;
            optInFastPeriod = (tempInteger) as i32;
            tempMAType = (optInSlowMAType) as usize;
            optInSlowMAType = optInFastMAType;
            optInFastMAType = (tempMAType) as i32;
        }
        lookbackLargest = self.ma_lookback(optInFastPeriod, optInFastMAType);
        tempInteger = self.ma_lookback(optInSlowPeriod, optInSlowMAType);
        if tempInteger > lookbackLargest {
            lookbackLargest = tempInteger;
        }
        lookbackSignal = self.ma_lookback(optInSignalPeriod, optInSignalMAType);
        lookbackTotal = lookbackSignal + lookbackLargest;
        if startIdx < lookbackTotal {
            startIdx = lookbackTotal;
        }
        if startIdx > endIdx {
            (*outBegIdx) = 0;
            (*outNBElement) = 0;
            return RetCode::Success;
        }
        tempInteger = endIdx - startIdx + 1 + lookbackSignal;
        fastMABuffer = vec![0.0_f64; (tempInteger * 1) as usize];
        slowMABuffer = vec![0.0_f64; (tempInteger * 1) as usize];
        tempInteger = startIdx - lookbackSignal;
        retCode = self.ma_unguarded(tempInteger, endIdx, inReal, optInSlowPeriod, optInSlowMAType, &mut outBegIdx1, &mut outNbElement1, &mut slowMABuffer[..]);
        if retCode != RetCode::Success {
            (*outBegIdx) = 0;
            (*outNBElement) = 0;
            return retCode;
        }
        retCode = self.ma_unguarded(tempInteger, endIdx, inReal, optInFastPeriod, optInFastMAType, &mut outBegIdx2, &mut outNbElement2, &mut fastMABuffer[..]);
        if retCode != RetCode::Success {
            (*outBegIdx) = 0;
            (*outNBElement) = 0;
            return retCode;
        }
        if outBegIdx1 != tempInteger || outBegIdx2 != tempInteger || outNbElement1 != outNbElement2 || outNbElement1 != endIdx - startIdx + 1 + lookbackSignal {
            (*outBegIdx) = 0;
            (*outNBElement) = 0;
            return RetCode::BadParam;
        }
        // for( i = 0; i < outNbElement1; i += 1 )
        i = 0;
        while i < outNbElement1 {
            *fastMABuffer.as_mut_ptr().add(i) = *fastMABuffer.as_ptr().add(i) - *slowMABuffer.as_ptr().add(i);
            i += 1;
        }
        {
            let _n = ((endIdx - startIdx + 1) * 1) as usize;
            let _di = (0) as usize;
            let _si = (lookbackSignal) as usize;
            outMACD[_di.._di + _n].copy_from_slice(&fastMABuffer[_si.._si + _n]);
        };
        retCode = self.ma_unguarded(0, outNbElement1 - 1, &fastMABuffer, optInSignalPeriod, optInSignalMAType, &mut outBegIdx2, &mut outNbElement2, outMACDSignal);
        if retCode != RetCode::Success {
            (*outBegIdx) = 0;
            (*outNBElement) = 0;
            return retCode;
        }
        // for( i = 0; i < outNbElement2; i += 1 )
        i = 0;
        while i < outNbElement2 {
            *outMACDHist.as_mut_ptr().add(i) = ((*outMACD.as_ptr().add(i) - *outMACDSignal.as_ptr().add(i)) as f64);
            i += 1;
        }
        (*outBegIdx) = startIdx;
        (*outNBElement) = outNbElement2;
        return RetCode::Success;
        } // unsafe
    }
}
/***************/
/* End of File */
/***************/
