from RFEM.initModel import Model, Calculate_all
from RFEM.enums import SurfaceGeometry, LineSupportType, SurfaceLoadDistribution, SurfaceLoadDirection
from RFEM.BasicObjects.material import Material
from RFEM.BasicObjects.node import Node
from RFEM.BasicObjects.line import Line
from RFEM.BasicObjects.thickness import Thickness
from RFEM.BasicObjects.surface import Surface
from RFEM.TypesForLines.lineSupport import LineSupport
from RFEM.LoadCasesAndCombinations.staticAnalysisSettings import StaticAnalysisSettings
from RFEM.LoadCasesAndCombinations.loadCase import LoadCase
from RFEM.Loads.surfaceLoad import SurfaceLoad
from RFEM.Results.resultTables import ResultTables, GetMaxValue, GetMinValue

diameter = 8
height = 12
util = 0.8
wallThickness = 0.007

maxStress = 200

while maxStress > 50:
    Model(True, "tankApp.rf6")
    Model.clientModel.service.delete_all()
    Model.clientModel.service.begin_modification()

    Material(1, 'S235')

    Node(1, diameter/2,0,0)
    Node(2, diameter/2,0,-height)

    Line.Circle(1, [0,0,0], diameter/2, [0,0,1])
    Line.Circle(2, [0,0,-height], diameter/2, [0,0,1])
    Line(3, '1 2')

    Thickness(1, 'wall', 1, wallThickness)

    Surface.Standard(1, SurfaceGeometry.GEOMETRY_QUADRANGLE, [1, 2, 0 , 0], '1 2 3', 1)

    LineSupport(1, '1', LineSupportType.HINGED)

    StaticAnalysisSettings()

    LoadCase(1, 'Pressure', [False])

    loadHeight = util * height

    SurfaceLoad.Force(1, 1, '1',
                    SurfaceLoadDirection.LOAD_DIRECTION_LOCAL_Z,
                    SurfaceLoadDistribution.LOAD_DISTRIBUTION_VARYING_IN_Z,
                    [[-loadHeight, -loadHeight, 0], [0, loadHeight, 9.81*loadHeight*1000]])


    Model.clientModel.service.finish_modification()

    Calculate_all()

    maxStressTable = ResultTables.SurfacesEquivalentStressesMises()
    maxStress = GetMaxValue(maxStressTable, 'equivalent_stresses_sigma_eqv_max') / 1000000

    print(f"For thickness {wallThickness * 1000} mm, maximum stress on the tank wall is {maxStress} mPa.")

    wallThickness += 0.001

print(f"Selected thickness is {round(wallThickness, 2)*1000 - 1} mm.")