/* 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
 *  -------------------------------------------------------------------
 *  112400 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::atr`]: the number of leading input values consumed before the
    /// first output value can be produced.
    ///
    /// # Arguments
    ///
    /// * `optInTimePeriod` — Smoothing period (default 14, range 1..=100000)
    ///
    /// Returns `usize::MAX` when a parameter is out of range. Integer parameters accept `i32::MIN`
    /// to select their default value.
    #[inline]
    pub fn atr_lookback(&self, mut optInTimePeriod: i32) -> usize {
        if ((optInTimePeriod) as i32) == (i32::MIN) {
            optInTimePeriod = 14;
        } else if (((optInTimePeriod) as i32) < 1) || (((optInTimePeriod) as i32) > 100000) {
            return usize::MAX;
        }
        // The ATR lookback is the sum of:
        //    1 + (optInTimePeriod - 1)
        //
        // Where 1 is for the True Range, and
        // (optInTimePeriod-1) is for the simple
        // moving average.
        return (optInTimePeriod + self.unstable_period[FuncUnstId::Atr as usize]) as usize;
    }
    /// Wilder-smoothed average of the True Range over a period, measuring price volatility
    /// regardless of direction. Higher ATR means greater volatility; no directional bias.
    ///
    /// # Formula
    ///
    /// ```text
    /// TR_t = max(high-low, |prevClose-high|, |prevClose-low|)
    /// ATR seed = simple average of first `period` TR values
    /// ATR_t = (ATR_{t-1} * (period-1) + TR_t) / period
    /// ```
    ///
    /// # 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.
    /// * `optInTimePeriod` — Smoothing period (default 14, range 1..=100000)
    /// * `outBegIdx` — Set to the input index of the first output value.
    /// * `outNBElement` — Set to the number of output values written.
    /// * `outReal` — Average True Range value.
    ///
    /// 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 core = Core::new();
    /// let mut out_beg = 0;
    /// let mut out_nb = 0;
    /// let mut out = vec![0.0; 252];
    ///
    /// let ret = core.atr(
    ///     0, high.len() - 1, &high, &low, &close, 14,
    ///     &mut out_beg, &mut out_nb, &mut out,
    /// );
    /// assert_eq!(ret, RetCode::Success);
    /// assert!(out_nb > 0);
    /// ```
    ///
    /// # See also
    ///
    /// [`Core::trange`] · [`Core::natr`] · [`Core::sma`] · [`Core::ema`]
    ///
    /// # References
    ///
    /// * J. Welles Wilder, *New Concepts in Technical Trading Systems*, Trend Research (ISBN
    ///   0894590278)
    ///
    /// Further reading: [ta-lib.org/functions/atr](https://ta-lib.org/functions/atr/)
    #[doc(alias = "AverageTrueRange")]
    pub fn atr(
        &self,
        startIdx: usize,
        endIdx: usize,
        inHigh: &[f64],
        inLow: &[f64],
        inClose: &[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) < 1) || (((optInTimePeriod) as i32) > 100000) {
            return RetCode::BadParam;
        }
        let mut startIdx = startIdx;
        let mut retCode: RetCode = RetCode::Success;
        let mut outIdx: usize = 0_usize;
        let mut today: usize = 0_usize;
        let mut lookbackTotal: usize = 0_usize;
        let mut nbATR: usize = 0_usize;
        let mut outBegIdx1: usize = 0_usize;
        let mut outNbElement1: usize = 0_usize;
        let mut prevATR: f64 = 0.0_f64;
        let mut tempBuffer: Vec<f64> = Vec::new();
        // Average True Range is the greatest of the following:
        //
        //  val1 = distance from today's high to today's low.
        //  val2 = distance from yesterday's close to today's high.
        //  val3 = distance from yesterday's close to today's low.
        //
        // These value are averaged for the specified period using
        // Wilder method. This method have an unstable period comparable
        // to and Exponential Moving Average (EMA).
        (*outBegIdx) = 0;
        (*outNBElement) = 0;
        // Adjust startIdx to account for the lookback period.
        lookbackTotal = self.atr_lookback(optInTimePeriod);
        if startIdx < lookbackTotal {
            startIdx = lookbackTotal;
        }
        // Make sure there is still something to evaluate.
        if startIdx > endIdx {
            return RetCode::Success;
        }
        // Trap the case where no smoothing is needed.
        if optInTimePeriod <= 1 {
            // No smoothing needed. Just do a TRANGE.
            return self.trange_unguarded(startIdx, endIdx, inHigh, inLow, inClose, outBegIdx, outNBElement, outReal);
        }
        // Allocate an intermediate buffer for TRANGE.
        tempBuffer = vec![0.0_f64; ((lookbackTotal + (endIdx - startIdx) + 1) * 1) as usize];
        // Do TRANGE in the intermediate buffer.
        retCode = self.trange_unguarded(startIdx - lookbackTotal + 1, endIdx, inHigh, inLow, inClose, &mut outBegIdx1, &mut outNbElement1, &mut tempBuffer[..]);
        if retCode != RetCode::Success {
            return retCode;
        }
        // First value of the ATR is a simple Average of
        // the TRANGE output for the specified period.
        retCode = self.sma_unguarded((optInTimePeriod - 1) as usize, (optInTimePeriod - 1) as usize, &tempBuffer, optInTimePeriod, &mut outBegIdx1, &mut outNbElement1, std::slice::from_mut(&mut prevATR));
        if retCode != RetCode::Success {
            return retCode;
        }
        // Subsequent value are smoothed using the
        // previous ATR value (Wilder's approach).
        //  1) Multiply the previous ATR by 'period-1'.
        //  2) Add today TR value.
        //  3) Divide by 'period'.
        today = (optInTimePeriod) as usize;
        outIdx = (self.unstable_period[FuncUnstId::Atr as usize]) as usize;
        // Skip the unstable period.
        while outIdx != 0 {
            prevATR *= ((optInTimePeriod - 1) as f64);
            prevATR += tempBuffer[{ let _v = today; today += 1; _v }];
            prevATR /= ((optInTimePeriod) as f64);
            outIdx -= 1;
        }
        // Now start to write the final ATR in the caller
        // provided outReal.
        outIdx = 1;
        outReal[0] = prevATR;
        // Now do the number of requested ATR.
        nbATR = endIdx - startIdx + 1;
        while { nbATR = nbATR.wrapping_sub(1); nbATR } != 0 {
            prevATR *= ((optInTimePeriod - 1) as f64);
            prevATR += tempBuffer[{ let _v = today; today += 1; _v }];
            prevATR /= ((optInTimePeriod) as f64);
            outReal[outIdx] = prevATR;
            outIdx += 1;
        }
        (*outBegIdx) = startIdx;
        (*outNBElement) = outIdx;
        return retCode;
    }
    /// Unchecked variant of [`Core::atr`], used for internal cross-indicator calls.
    ///
    /// Skips parameter validation and uses unchecked indexing internally. Every argument must
    /// satisfy the constraints documented on [`Core::atr`]; 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::atr`].
    #[inline]
    pub fn atr_unguarded(
        &self,
        mut startIdx: usize,
        endIdx: usize,
        inHigh: &[f64],
        inLow: &[f64],
        inClose: &[f64],
        mut optInTimePeriod: i32,
        outBegIdx: &mut usize,
        outNBElement: &mut usize,
        outReal: &mut [f64],
    ) -> RetCode {
        let mut retCode: RetCode = RetCode::Success;
        let mut outIdx: usize = 0_usize;
        let mut today: usize = 0_usize;
        let mut lookbackTotal: usize = 0_usize;
        let mut nbATR: usize = 0_usize;
        let mut outBegIdx1: usize = 0_usize;
        let mut outNbElement1: usize = 0_usize;
        let mut prevATR: f64 = 0.0_f64;
        let mut tempBuffer: Vec<f64> = Vec::new();
        unsafe {
        assert!(endIdx < inHigh.len());
        assert!(endIdx < inLow.len());
        assert!(endIdx < inClose.len());
        let _assertLb = self.atr_lookback(optInTimePeriod);
        let _assertStart = if startIdx > _assertLb { startIdx } else { _assertLb };
        assert!(_assertStart > endIdx || endIdx - _assertStart < outReal.len());
        (*outBegIdx) = 0;
        (*outNBElement) = 0;
        lookbackTotal = self.atr_lookback(optInTimePeriod);
        if startIdx < lookbackTotal {
            startIdx = lookbackTotal;
        }
        if startIdx > endIdx {
            return RetCode::Success;
        }
        if optInTimePeriod <= 1 {
            return self.trange_unguarded(startIdx, endIdx, inHigh, inLow, inClose, outBegIdx, outNBElement, outReal);
        }
        tempBuffer = vec![0.0_f64; ((lookbackTotal + (endIdx - startIdx) + 1) * 1) as usize];
        retCode = self.trange_unguarded(startIdx - lookbackTotal + 1, endIdx, inHigh, inLow, inClose, &mut outBegIdx1, &mut outNbElement1, &mut tempBuffer[..]);
        if retCode != RetCode::Success {
            return retCode;
        }
        retCode = self.sma_unguarded((optInTimePeriod - 1) as usize, (optInTimePeriod - 1) as usize, &tempBuffer, optInTimePeriod, &mut outBegIdx1, &mut outNbElement1, std::slice::from_mut(&mut prevATR));
        if retCode != RetCode::Success {
            return retCode;
        }
        today = (optInTimePeriod) as usize;
        outIdx = (self.unstable_period[FuncUnstId::Atr as usize]) as usize;
        while outIdx != 0 {
            prevATR *= ((optInTimePeriod - 1) as f64);
            prevATR += *tempBuffer.as_ptr().add({ let _v = today; today += 1; _v });
            prevATR /= ((optInTimePeriod) as f64);
            outIdx -= 1;
        }
        outIdx = 1;
        *outReal.as_mut_ptr().add(0) = prevATR;
        nbATR = endIdx - startIdx + 1;
        while { nbATR = nbATR.wrapping_sub(1); nbATR } != 0 {
            prevATR *= ((optInTimePeriod - 1) as f64);
            prevATR += *tempBuffer.as_ptr().add({ let _v = today; today += 1; _v });
            prevATR /= ((optInTimePeriod) as f64);
            *outReal.as_mut_ptr().add(outIdx) = prevATR;
            outIdx += 1;
        }
        (*outBegIdx) = startIdx;
        (*outNBElement) = outIdx;
        return retCode;
        } // unsafe
    }
}
/***************/
/* End of File */
/***************/
