// SPDX-License-Identifier: MIT OR Apache-2.0
// Copyright (c) 2025 lacklustr@protonmail.com https://github.com/eadf

use crate::common::macros::integrity_assert;
use crate::corner_table::CornerIndex;
use crate::util::index_pool::PoolIndex;

#[repr(transparent)]
#[derive(Clone, Copy, PartialEq, Eq, Ord, Hash, PartialOrd)]
/// A triangle index is corner index / 3
pub(crate) struct TriangleIndex(pub(crate) u32);

impl PoolIndex for TriangleIndex {}

impl TriangleIndex {
    pub const INVALID: TriangleIndex = TriangleIndex(u32::MAX);

    #[inline(always)]
    pub fn is_valid(self) -> bool {
        self.0 != Self::INVALID.0
    }

    #[inline(always)]
    pub fn base_corner(self) -> CornerIndex {
        integrity_assert!(self.is_valid());
        if cfg!(any(feature = "integrity_check", debug_assertions)) {
            CornerIndex(
                self.0
                    .checked_mul(3)
                    .expect("Triangle index overflow in base_corner"),
            )
        } else {
            CornerIndex(self.0 * 3)
        }
    }

    #[inline(always)]
    /// returns all the corners of the triangle (corner,corner.next,corner.prev)
    pub fn corners(self) -> [CornerIndex; 3] {
        let c = self.base_corner();
        [c, CornerIndex(c.0 + 1), CornerIndex(c.0 + 2)]
    }
}
