# -*- coding: utf-8 -*-
__author__ = 'TUMCIVIL'
__version__ = '2.0.0'
__title__ = 'เซ็ตระดับท้องผนัง\nชนหลังฐานราก'
__doc__ = """Created by : TUMCIVIL TEAM
Version : 2.0.0
Update : วันที่ 03-03-2025
_________________________________________________________________
รายการ :
เซ็ตระดับท้องผนังชนระดับหลังฐานราก

_________________________________________________________________
ข้อจำกัดการใช้งาน :
1.ไม่สามารถใช้กับผนังที่ Slope ได้
2.ไม่สามารถใช้กับผนังที่สร้างจาก Model In-Place ได้
_________________________________________________________________
วิธีการใช้ :
1.เลือกฐานราก
2.เลือกผนังที่ต้องการเช็คระดับปลาย ต้องการออกกด Esc

   

 """
# for timing -------------------------------------------------------------------
# import pyrevit.coreutils as cor
# from pyrevit.coreutils import Timer
# timer = Timer()
# ------------------------------------------------------------------------------
import sys
import re
import Autodesk
from Autodesk.Revit.DB import *
from Autodesk.Revit.UI import *
import Autodesk.Revit.DB as DB
from Autodesk.Revit.DB.Structure import *
from Autodesk.Revit.DB.Structure import Rebar as rb
import pyrevit

import  os
from pyrevit import forms, revit
from Autodesk.Revit.DB import *
from Autodesk.Revit.DB import (BuiltInParameter)

#>>>>>>>>>> .NET IMPORTS
import clr
clr.AddReference("System.Windows.Forms")
clr.AddReference("System")
from System.Collections.Generic import List
from System.Windows.Controls import ComboBoxItem
import wpf
from Autodesk.Revit.UI.Selection    import ISelectionFilter, ObjectType, Selection

#>>>>>>>>>> CUSTOM IMPORTS
from Snippets._convert_units import convert_internal_units
from Snippets._level import levels,get_levels_walls
from Snippets._level import *

doc   = __revit__.ActiveUIDocument.Document
uidoc = __revit__.ActiveUIDocument
app   = __revit__.Application

#>>>>>>>>> LIMIT SELECTION
class CustomISelectionFilter(ISelectionFilter):
    """Filter user selection to certain element."""
    def __init__(self, cats):
        self.cats = cats
        # print("self.cats = {}".format(self.cats))
    def AllowElement(self, e):
        if str(e.Category.Id) == str(self.cats):
            return True
        #     print("return = True")
        # print("return = False")
        return False

class ISelectionFilter_Classes(ISelectionFilter):
    def __init__(self, allowed_types):
        """ ISelectionFilter made to filter with types
        :param allowed_types: list of allowed Types"""
        self.allowed_types = allowed_types

    def AllowElement(self, element):
        if type(element) in self.allowed_types:
            return True
        # else:
        #     return False

#>>>>>>>>>> PICK COLUMN
def pick_wall(given_uidoc = uidoc):
    """Function to promt user to select a wall element in Revit UI."""
    wall_ref = given_uidoc.Selection.PickObject(ObjectType.Element, CustomISelectionFilter("-2000011"), "Select a Wall")    # -2000011 <- Id of OST_Walls
    wall     = given_uidoc.Document.GetElement(wall_ref)
    return wall

def pick_beam(given_uidoc = uidoc):
    """Function to promt user to select a column element in Revit UI."""
    beam_ref = given_uidoc.Selection.PickObjects(ObjectType.Element, CustomISelectionFilter("-2001320"), "เลือกคาน")    # -2001320 <- Id of OST_StructuralFraming
    beam     = given_uidoc.Document.GetElement(beam_ref)
    return beam
def pick_column(given_uidoc = uidoc,text = "เลือกเสา" ):
    """Function to promt user to select a column element in Revit UI."""
    # forms.WarningBar(title='Select Walls.')
    column_ref = given_uidoc.Selection.PickObject(ObjectType.Element, CustomISelectionFilter("-2001330"), text)    # -2001330 <- Id of OST_StructuralColumns
    column     = given_uidoc.Document.GetElement(column_ref)
    return column
def pick_footing(given_uidoc = uidoc,text = "เลือกฐานราก" ):
    """Function to promt user to select a column element in Revit UI."""
    # forms.WarningBar(title='Select Walls.')
    footing_ref = given_uidoc.Selection.PickObject(ObjectType.Element, CustomISelectionFilter("-2001300"), text)    # -2001330 <- Id of OST_StructuralFoundation
    footing     = given_uidoc.Document.GetElement(footing_ref)
    return footing

def get_selected_walls(uidoc, exitscript = True):
    """Function to Pick Walls. Currently selected walls will be pre-selected."""
    doc       = uidoc.Document
    selection = uidoc.Selection  # type: Selection

    selected_elements = [doc.GetElement(e_id) for e_id in selection.GetElementIds()]
    selected_walls    = [e for e in selected_elements if type(e) == Wall]


    ref_walls         = [Reference(r) for r in selected_walls]
    ref_preselection  = List[Reference](ref_walls)

    # Pick Walls (exterior walls are preselected)
    ISF_Rooms      = ISelectionFilter_Classes([Wall,])
    selected_walls = []

    try:
        with forms.WarningBar(title='Select Walls.'):
            ref_selected_walls = selection.PickObjects(ObjectType.Element,
                                                       ISF_Rooms,
                                                       'Select Rooms',
                                                       ref_preselection)

        selected_walls  = [doc.GetElement(ref) for ref in ref_selected_walls]
    except:
        pass

    if not selected_walls:
        error_msg = 'No Walls were selected.\nPlease Try Again'
        forms.alert(error_msg, title='Wall Selection has Failed.', exitscript=exitscript)

    return selected_walls

def get_selected_beams(uidoc, exitscript = True):
    """Function to Pick Beams. Currently selected beams will be pre-selected."""
    doc       = uidoc.Document
    selection = uidoc.Selection  # type: Selection

    selected_beams = []
    # ISF_Rooms      = CustomISelectionFilter("-2001352")
    ISF_Rooms      = CustomISelectionFilter("-2001320")
    selected_elements = [doc.GetElement(e_id) for e_id in selection.GetElementIds()]
    selected_beams    = [e for e in selected_elements]

    ref_beams         = [Reference(r) for r in selected_beams]
    ref_preselection  = List[Reference](ref_beams)

    # Pick Beams (exterior walls are preselected)

    try:
        with forms.WarningBar(title='โปรดเลือกคานที่เชื่อมหัวเสาเสร็จแล้วกด Finish.'):
            ref_selected_beams = selection.PickObjects(ObjectType.Element,
                                                       ISF_Rooms,
                                                       'โปรดเลือกคานเสร็จแล้วกด Finish',
                                                       ref_preselection)

        selected_beams  = [doc.GetElement(ref) for ref in ref_selected_beams]
    except:
        pass

    if not selected_beams:
        error_msg = 'No Beams were selected.\nPlease Try Again'
        forms.alert(error_msg, title='Beams Selection has Failed.', exitscript=exitscript)

    return selected_beams

def get_selected_columns(uidoc, exitscript = True):
    """Function to Pick Beams. Currently selected beams will be pre-selected."""
    doc       = uidoc.Document
    selection = uidoc.Selection  # type: Selection

    selected_columns = []
    # ISF_Rooms      = CustomISelectionFilter("-2001352")
    ISF_Rooms      = CustomISelectionFilter("-2001330")
    selected_elements = [doc.GetElement(e_id) for e_id in selection.GetElementIds()]
    selected_columns    = [e for e in selected_elements]

    ref_columns         = [Reference(r) for r in selected_columns]
    ref_preselection  = List[Reference](ref_columns)

    # Pick Columns (exterior walls are preselected)

    try:
        with forms.WarningBar(title='โปรดเลือกเสาที่ต้องการเชื่อมกับหลังฐานรากเสร็จแล้วกด Finish.'):
            ref_selected_columns = selection.PickObjects(ObjectType.Element,
                                                       ISF_Rooms,
                                                       'โปรดเลือกคานเสร็จแล้วกด Finish',
                                                       ref_preselection)

        selected_columns  = [doc.GetElement(ref) for ref in ref_selected_columns]
    except:
        pass

    if not selected_columns:
        error_msg = 'No Beams were selected.\nPlease Try Again'
        forms.alert(error_msg, title='Beams Selection has Failed.', exitscript=exitscript)

    return selected_columns

def get_selected_elements(uidoc = uidoc, exitscript=True):
    """Property that retrieves selected views or promt user to select some from the dialog box."""
    doc       = uidoc.Document
    selection = uidoc.Selection  # type: Selection

    try:
        selected_elements = [doc.GetElement(e_id) for e_id in selection.GetElementIds()]
        if not selected_elements:
            forms.alert("No elements  were selected.\nPlease, try again.", exitscript=exitscript)
    except:
        return

    return selected_elements


if __name__ == '__main__':

    out = []
    out3 = []
    levels_model = levels()

    # >>>>>>>>>> SELECT MAIN FOOTING
    try:    Selected_footing = pick_footing(uidoc,"เลือกฐานราก")
    except: forms.alert("ฐานรากไม่ได้ถูกเลือกรายการถูกยกเลิก.",exitscript=True,title="Script Canceled.")


    top_Level_Footing = Selected_footing.get_Parameter(BuiltInParameter.STRUCTURAL_ELEVATION_AT_TOP).AsDouble()
    Bottom_Level_Footing = Selected_footing.get_Parameter(BuiltInParameter.STRUCTURAL_ELEVATION_AT_BOTTOM).AsDouble()
    Level_Footing = Selected_footing.get_Parameter(BuiltInParameter.SCHEDULE_LEVEL_PARAM).AsElementId()

    # print ("top_Level_Footing = {}".format(top_Level_Footing))
    # print ("Bottom_Level_Footing = {}".format(Bottom_Level_Footing))
    # print ("Level_Footing = {}".format(Level_Footing))
    # print ("out3 = {}".format(out3))

    for i in out3:
        if i[2]  == Level_Footing:
            Level_Footing_Name = i[2]
            Level_Footing_Value = i[1]
            # print ("i[2] = {}".format(i[2]))
            # print ("Level_Footing_Name = {}".format(Level_Footing_Name))
            # print ("Level_Footing_Value = {}".format(Level_Footing_Value))

    Main_Top_Constraint = top_Level_Footing
    # print ("Main_Top_Constraint = {}".format(convert_internal_units(Main_Top_Constraint, False, "mm")))

    # >>>>>>>>>> SELECT Wall
    with forms.WarningBar(title="Pick Wall to top Footing: (Exit Click Esc)", handle_esc=True):
        while True:

            # >>>>>>>>>> PICK WALL
            try:
                Match_wall = pick_wall(uidoc)
            except:
                break
            if not Match_wall: break
            levels_wall = get_levels_walls(levels_model, Match_wall)
            Match_Top_Constraint = levels_wall[1]
            Match_Bottom_Constraint = levels_wall[0]
            wall_location = Match_wall.Location
            wall_curve = wall_location.Curve
            # print("Match_Top_Constraint = {}".format(Match_Top_Constraint))
            # print("Match_Top_Constraint2 = {}".format(round(convert_internal_units(float(Match_Top_Constraint), False, units='mm')),0))
            # print("Match_Bottom_Constraint = {}".format(round(convert_internal_units(float(Match_Bottom_Constraint), False, units='mm')),0))

            Main_Top_Constraint_Id = Match_wall.get_Parameter(BuiltInParameter.WALL_HEIGHT_TYPE).AsElementId()
            # print("Main_Top_Constraint_Id = {}".format(Main_Top_Constraint_Id))
            # >>>>>>>>>> MATCH WALL PARAMETERS
            match_base_offset = Match_wall.get_Parameter(BuiltInParameter.WALL_BASE_OFFSET).AsDouble()
            match_unconnected_height = Match_wall.get_Parameter(BuiltInParameter.WALL_USER_HEIGHT_PARAM).AsDouble()
            match_Z_Top = Match_Top_Constraint - Main_Top_Constraint

            if isinstance(wall_curve, Line):
                match_Z_Bottom           = (Main_Top_Constraint)-Match_wall.Location.Curve.Origin.Z
            elif isinstance(wall_curve, Arc):
                match_Z_Bottom           = (Main_Top_Constraint)-Match_wall.Location.Curve.Center.Z





            # match_Z_Bottom = (Main_Top_Constraint) - Match_wall.Location.Curve.Origin.Z
            # match_Z_Bottom         = Main_Top_Constraint-(Match_wall.Location.Curve.Origin.Z + match_base_offset)

            # convert_internal_units(float(match_Z_Bottom), False, units='mm')
            # print("Match_wall.Location.Curve.Origin.Z = {}".format(convert_internal_units(float(Match_wall.Location.Curve.Origin.Z), False, units='mm')))
            # print("match_base_offset = {}".format(convert_internal_units(float(match_base_offset), False, units='mm')))
            # print("match_unconnected_height = {}".format(convert_internal_units(float(match_unconnected_height), False, units='mm')))
            # print("match_Z_Top = {}".format(convert_internal_units(float(match_Z_Top), False, units='mm')))
            # print("match_Z_Bottom = {}".format(convert_internal_units(float(match_Z_Bottom), False, units='mm')))

            with Transaction(doc, "Reinforce") as t:
                t.Start()
                Match_wall.get_Parameter(BuiltInParameter.WALL_HEIGHT_TYPE).Set(ElementId.InvalidElementId)
                Match_wall.get_Parameter(BuiltInParameter.WALL_USER_HEIGHT_PARAM).Set(match_Z_Top)
                Match_wall.get_Parameter(BuiltInParameter.WALL_BASE_OFFSET).Set(match_Z_Bottom)

                t.Commit()


# for timing -------------------------------------------------------------------
# print("====" * 20)
# endtime = timer.get_time()
# print("Time been used = {} sec.".format(endtime))
# currentDate = cor.current_date()
# currentTime = cor.current_time()
# print ("Date : {} ; {}".format(currentDate,currentTime))
# print ("Credited by : {}".format(__author__))
# print("====" * 20)
# ------------------------------------------------------------------------------