/* 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
 *  -------------------------------------------------------------------
 *  JP       John Price <jp_talib@gcfl.net>
 *  MF       Mario Fortier
 *  AM       Adrian Michel <http://amichel.com>
 *
 * Change history:
 *
 *  MMDDYY BY      Description
 *  -------------------------------------------------------------------
 *  070203 JP      Initial.
 *  072106 MF,AM   Fix #1526632. Add missing atan().
 */

// 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::linearreg_angle`]: the number of leading input values consumed
    /// before the first output value can be produced.
    ///
    /// # Arguments
    ///
    /// * `optInTimePeriod` — Number of points in the regression window (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 linearreg_angle_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 - 1) as usize;
    }
    /// The angle, in degrees, of the least-squares best-fit line over the last N points. It is the
    /// LINEARREG_SLOPE value passed through atan and converted to degrees. Positive angle = rising
    /// fit line, negative = falling; magnitude reflects steepness.
    ///
    /// # Formula
    ///
    /// ```text
    /// m = (N·SumXY − SumX·SumY) / (SumX² − N·SumXSqr), with SumX=N(N−1)/2, SumXSqr=N(N−1)(2N−1)/6; angle = atan(m)·(180/π)
    /// ```
    ///
    /// # Arguments
    ///
    /// * `startIdx` — Start index of the requested calculation range.
    /// * `endIdx` — End index of the requested calculation range (inclusive).
    /// * `inReal` — Input series to regress.
    /// * `optInTimePeriod` — Number of points in the regression window (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` — Regression line slope expressed as an angle in degrees.
    ///
    /// 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 out = vec![0.0; 252];
    ///
    /// let ret = core.linearreg_angle(
    ///     0, data.len() - 1, &data, 14,
    ///     &mut out_beg, &mut out_nb, &mut out,
    /// );
    /// assert_eq!(ret, RetCode::Success);
    /// assert!(out_nb > 0);
    /// ```
    ///
    /// # See also
    ///
    /// [`Core::linearreg`] · [`Core::linearreg_slope`] · [`Core::linearreg_intercept`] ·
    /// [`Core::tsf`]
    ///
    /// Further reading:
    /// [ta-lib.org/functions/linearreg_angle](https://ta-lib.org/functions/linearreg_angle/)
    #[doc(alias = "LinearRegressionAngle")]
    #[doc(alias = "LeastSquaresAngle")]
    pub fn linearreg_angle(
        &self,
        startIdx: usize,
        endIdx: usize,
        inReal: &[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 outIdx: usize = 0_usize;
        let mut today: usize = 0_usize;
        let mut lookbackTotal: usize = 0_usize;
        let mut SumX: f64 = 0.0_f64;
        let mut SumXY: f64 = 0.0_f64;
        let mut SumY: f64 = 0.0_f64;
        let mut SumXSqr: f64 = 0.0_f64;
        let mut Divisor: f64 = 0.0_f64;
        let mut m: f64 = 0.0_f64;
        let mut i: usize = 0_usize;
        let mut tempValue1: f64 = 0.0_f64;
        // Linear Regression is a concept also known as the
        // "least squares method" or "best fit." Linear
        // Regression attempts to fit a straight line between
        // several data points in such a way that distance
        // between each data point and the line is minimized.
        //
        // For each point, a straight line over the specified
        // previous bar period is determined in terms
        // of y = b + m*x:
        //
        // TA_LINEARREG          : Returns b+m*(period-1)
        // TA_LINEARREG_SLOPE    : Returns 'm'
        // TA_LINEARREG_ANGLE    : Returns 'm' in degree.
        // TA_LINEARREG_INTERCEPT: Returns 'b'
        // TA_TSF                : Returns b+m*(period)
        // Adjust startIdx to account for the lookback period.
        lookbackTotal = self.linearreg_angle_lookback(optInTimePeriod);
        if startIdx < lookbackTotal {
            startIdx = lookbackTotal;
        }
        // Make sure there is still something to evaluate.
        if startIdx > endIdx {
            (*outBegIdx) = 0;
            (*outNBElement) = 0;
            return RetCode::Success;
        }
        outIdx = 0;
        // Index into the output.
        today = startIdx;
        SumX = ((optInTimePeriod * (optInTimePeriod - 1)) as f64) * 0.5;
        SumXSqr = ((optInTimePeriod * (optInTimePeriod - 1) * (2 * optInTimePeriod - 1) / 6) as f64);
        Divisor = SumX * SumX - ((optInTimePeriod) as f64) * SumXSqr;
        while today <= endIdx {
            SumXY = 0.0;
            SumY = 0.0;
            // for( i = (optInTimePeriod) as usize; { let _v = i; i = i.wrapping_sub(1); _v } != 0;  )
            i = (optInTimePeriod) as usize;
            while { let _v = i; i = i.wrapping_sub(1); _v } != 0 {
                tempValue1 = inReal[today - i];
                SumY += tempValue1;
                SumXY += (i as f64) * tempValue1;
            }
            m = (((optInTimePeriod) as f64) * SumXY - SumX * SumY) / Divisor;
            outReal[outIdx] = (m).atan() * (180.0 / 3.141592653589793);
            outIdx += 1;
            today += 1;
        }
        (*outBegIdx) = startIdx;
        (*outNBElement) = outIdx;
        return RetCode::Success;
    }
    /// Unchecked variant of [`Core::linearreg_angle`], used for internal cross-indicator calls.
    ///
    /// Skips parameter validation and uses unchecked indexing internally. Every argument must
    /// satisfy the constraints documented on [`Core::linearreg_angle`]; 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::linearreg_angle`].
    #[inline]
    pub fn linearreg_angle_unguarded(
        &self,
        mut startIdx: usize,
        endIdx: usize,
        inReal: &[f64],
        mut optInTimePeriod: i32,
        outBegIdx: &mut usize,
        outNBElement: &mut usize,
        outReal: &mut [f64],
    ) -> RetCode {
        let mut outIdx: usize = 0_usize;
        let mut today: usize = 0_usize;
        let mut lookbackTotal: usize = 0_usize;
        let mut SumX: f64 = 0.0_f64;
        let mut SumXY: f64 = 0.0_f64;
        let mut SumY: f64 = 0.0_f64;
        let mut SumXSqr: f64 = 0.0_f64;
        let mut Divisor: f64 = 0.0_f64;
        let mut m: f64 = 0.0_f64;
        let mut i: usize = 0_usize;
        let mut tempValue1: f64 = 0.0_f64;
        unsafe {
        assert!(endIdx < inReal.len());
        let _assertLb = self.linearreg_angle_lookback(optInTimePeriod);
        let _assertStart = if startIdx > _assertLb { startIdx } else { _assertLb };
        assert!(_assertStart > endIdx || endIdx - _assertStart < outReal.len());
        lookbackTotal = self.linearreg_angle_lookback(optInTimePeriod);
        if startIdx < lookbackTotal {
            startIdx = lookbackTotal;
        }
        if startIdx > endIdx {
            (*outBegIdx) = 0;
            (*outNBElement) = 0;
            return RetCode::Success;
        }
        outIdx = 0;
        today = startIdx;
        SumX = ((optInTimePeriod * (optInTimePeriod - 1)) as f64) * 0.5;
        SumXSqr = ((optInTimePeriod * (optInTimePeriod - 1) * (2 * optInTimePeriod - 1) / 6) as f64);
        Divisor = SumX * SumX - ((optInTimePeriod) as f64) * SumXSqr;
        while today <= endIdx {
            SumXY = 0.0;
            SumY = 0.0;
            // for( i = (optInTimePeriod) as usize; { let _v = i; i = i.wrapping_sub(1); _v } != 0;  )
            i = (optInTimePeriod) as usize;
            while { let _v = i; i = i.wrapping_sub(1); _v } != 0 {
                tempValue1 = *inReal.as_ptr().add(today - i);
                SumY += tempValue1;
                SumXY += (i as f64) * tempValue1;
            }
            m = (((optInTimePeriod) as f64) * SumXY - SumX * SumY) / Divisor;
            *outReal.as_mut_ptr().add(outIdx) = (m).atan() * (180.0 / 3.141592653589793);
            outIdx += 1;
            today += 1;
        }
        (*outBegIdx) = startIdx;
        (*outNBElement) = outIdx;
        return RetCode::Success;
        } // unsafe
    }
}
/***************/
/* End of File */
/***************/
