"Add elevation data concrete columns in Model \n\n\n Updated : 01-05-2024 \n\n Shared by : TUMCIVIL"
__author__ = 'TUMCIVIL'
__version__ = '1.0.0'
__title__ = ' Add Elevation Columns'
# for timing -------------------------------------------------------------------
import pyrevit.coreutils as cor
from pyrevit.coreutils import Timer
timer = Timer()
# ------------------------------------------------------------------------------
import sys
import csv
import codecs
import os.path as op
from collections import defaultdict

from pyrevit import PyRevitException
from pyrevit import forms
from pyrevit import coreutils
from pyrevit import revit, DB, HOST_APP
from pyrevit import script
import Autodesk
from Autodesk.Revit.DB import *
from Autodesk.Revit.UI import *
import Autodesk.Revit.DB as DB
from Autodesk.Revit.DB.Structure import *
import re

doc = __revit__.ActiveUIDocument.Document
uidoc = __revit__.ActiveUIDocument

def checkParameter(parameter):
    storageType = parameter.StorageType
    if (storageType.ToString() == "ElementId"):
        value = parameter.AsValueString()
    return value

def levels():
    levels = DB.FilteredElementCollector(doc).OfCategory(DB.BuiltInCategory.OST_Levels) \
        .WhereElementIsNotElementType() \
        .ToElements()
    # print("levels = {}".format(levels))
    l = len(levels)
    # print("l = {}".format(l))
    # out3 = []
    for e3 in levels:
        p3 =[]
        name = e3.get_Parameter(BuiltInParameter.DATUM_TEXT).AsString()
        # name = e3.LookupParameter("Name").AsString()
        eleLev = e3.get_Parameter(BuiltInParameter.LEVEL_ELEV).AsDouble()
        # eleLev = e3.LookupParameter("Elevation").AsDouble()
        p3.append(name)
        p3.append(eleLev)
        # print("levels = {} , {}".format(name,eleLev))

        out3.append(p3)
    # for i in out3:
    # print("out3 = {}".format(out3))

def columns():
    columns = DB.FilteredElementCollector(doc).OfCategory(DB.BuiltInCategory.OST_StructuralColumns) \
        .WhereElementIsNotElementType() \
        .ToElements()

    for e in columns:
        p2 = []
        for j in e.Parameters:
            if j.IsShared and j.Definition.Name == "Name Tags":
                nameTags = e.get_Parameter(j.GUID).AsString()
        # typeName = e.get_Parameter(BuiltInParameter.ELEM_TYPE_PARAM)
        # value = checkParameter(typeName)
        baseLev = e.get_Parameter(BuiltInParameter.SCHEDULE_BASE_LEVEL_PARAM)
        value1 = checkParameter(baseLev)
        baseOff = e.get_Parameter(BuiltInParameter.SCHEDULE_BASE_LEVEL_OFFSET_PARAM).AsDouble()
        # print("baseLev = {} ,baseOff = {}".format(value1,baseOff))
        eleBase = [v[1]+baseOff for v in out3 if v[0].upper() == value1.strip("Up to level:").upper()]
        # print("eleBase = {}".format(eleBase))
        for i in eleBase:
            eleBaseConvert = UnitUtils.ConvertFromInternalUnits(i,UnitTypeId.Millimeters)
        # print("eleBaseConvert = {}".format(eleBaseConvert)) 
        if eleBaseConvert >= 0:
            eleBaseCombine = "+"+str(round(eleBaseConvert)).replace(".0","")
            # eleBaseCombine = "EL.+"+str(round(eleBaseConvert)).replace(".0","")
        elif eleBaseConvert < 0:
            eleBaseCombine = str(round(eleBaseConvert)).replace(".0","")
            # eleBaseCombine = "EL."+str(round(eleBaseConvert)).replace(".0","")
        # print("eleBaseCombine = {}".format(eleBaseCombine))

        topLev = e.get_Parameter(BuiltInParameter.SCHEDULE_TOP_LEVEL_PARAM)
        value2 = checkParameter(topLev)
        topOff = e.get_Parameter(BuiltInParameter.SCHEDULE_TOP_LEVEL_OFFSET_PARAM).AsDouble()
        # print("topLevs = {} ,topOff = {}".format(value2,topOff))
        eleTop = [v[1]+topOff for v in out3 if v[0].upper() == value2.strip("Up to level:").upper()]
        # print("eleTop = {}".format(eleTop))
        for i in eleTop:
            eleTopConvert = UnitUtils.ConvertFromInternalUnits(i,UnitTypeId.Millimeters)
        # print("eleTopConvert = {}".format(eleTopConvert)) 
        if eleTopConvert >= 0:
            eleTopCombine = "+"+str(round(eleTopConvert)).replace(".0","")
            # eleTopCombine = "EL.+"+str(round(eleTopConvert)).replace(".0","")
        elif eleTopConvert < 0:
            eleTopCombine = str(round(eleTopConvert)).replace(".0","")
            # eleTopCombine = "EL."+str(round(eleTopConvert)).replace(".0","")
        try:
            colLoMark = e.get_Parameter(BuiltInParameter.COLUMN_LOCATION_MARK).AsString()
            # print("colLoMark = {}".format(colLoMark))
        except:
            colLoMark = "-"

        loCombine = "[(EL."+eleBaseCombine+")"+"-(EL."+eleTopCombine+")];["+colLoMark+"]"
        # print("loCombine = {}".format(loCombine))

        q10 = eleBaseCombine
        q11 = eleTopCombine

        t = Transaction(doc, 'change parameter')
        t.Start()
        try:
            e.LookupParameter("Bottom of Column").Set(q10)
            e.LookupParameter("Top of Column").Set(q11)
            e.LookupParameter("Location").Set(loCombine)
        except:
            # TaskDialog.Show('error', 'error message')
            pass
        t.Commit()



if __name__ == "__main__":
    out2 = []
    out3 = []
    levels()
    columns()

# for timing -------------------------------------------------------------------
print("====" * 20)
print("ADD ELEVATION DATA COLUMNS COMPLETELY !")
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)
# ------------------------------------------------------------------------------