// Flange
// A flange is a flat rim, collar, or rib, typically forged or cast, that is used to strengthen an object, guide it, or attach it to another object. Flanges are known for their use in various applications, including piping, plumbing, and mechanical engineering, among others.

// Set units
@settings(defaultLengthUnit = in, kclVersion = 1.0)

// Define parameters
mountingHoleDia = .625
baseDia = 4.625
pipeDia = 1.25
totalThickness = 0.813
topTotalDiameter = 2.313
bottomThickness = 0.06
bottomTotalDiameter = 2.5
mountingHolePlacementDiameter = 3.5
baseThickness = .625
topTotalThickness = totalThickness - (bottomThickness + baseThickness)
nHoles = 4

// Add assertion so nHoles are always greater than 1
assert(nHoles, isGreaterThan = 1, error = "nHoles must be greater than 1")

// Create the circular pattern for the mounting holes
circles = startSketchOn(XY)
  |> circle(center = [mountingHolePlacementDiameter / 2, 0], radius = mountingHoleDia / 2)
  |> patternCircular2d(
       arcDegrees = 360,
       center = [0, 0],
       instances = nHoles,
       rotateDuplicates = true,
     )

// Create the base of the flange and add the mounting holes
flangeBase = startSketchOn(XY)
  |> circle(center = [0, 0], radius = baseDia / 2)
  |> subtract2d(tool = circles)
  |> extrude(length = baseThickness)

// Create the extrusion on the top of the flange base
topExtrusion = startSketchOn(flangeBase, face = END)
  |> circle(center = [0, 0], radius = topTotalDiameter / 2)
  |> extrude(length = topTotalThickness)

// Create the extrusion on the bottom of the flange base
bottomExtrusion = startSketchOn(flangeBase, face = START)
  |> circle(center = [0, 0], radius = bottomTotalDiameter / 2)
  |> extrude(length = bottomThickness)

// Cut a hole through the entire body
pipeHole = startSketchOn(topExtrusion, face = END)
  |> circle(center = [0, 0], radius = pipeDia / 2)
  |> extrude(%, length = -(topTotalThickness + baseThickness + bottomThickness))
