;; =============================================================================
;; HAM HO TRO: SPLIT STRING & GET FOLDER (GIU NGUYEN)
;; =============================================================================
(defun SplitStr ( str del / pos lst )
    (while (setq pos (vl-string-search del str))
        (setq lst (cons (substr str 1 pos) lst)
              str (substr str (+ 1 pos (strlen del)))
        )
    )
    (reverse (cons str lst))
)

(defun GetFolder ( msg / sh folder folderobj path )
    (vl-load-com)
    (setq sh (vlax-create-object "Shell.Application"))
    (setq folder (vlax-invoke-method sh 'BrowseForFolder 0 msg 0))
    (if folder
        (progn
            (setq folderobj (vlax-get-property folder 'Self))
            (setq path (vlax-get-property folderobj 'Path))
            (vlax-release-object folderobj)
            (vlax-release-object folder)
            (vlax-release-object sh)
            (if (not (eq (substr path (strlen path)) "\\"))
                (strcat path "\\")
                path
            )
        )
        (progn (vlax-release-object sh) nil)
    )
)

;; =============================================================================
;; CHUONG TRINH CHINH: VE_LINE_TU_DONG (DA NANG CAP FORMAT)
;; =============================================================================
(defun c:VE_LINE_TU_DONG11 ( / csvFile fDat outputFolder lineStr lineList lineType lineDesc 
                            textHeight yOffset dashLength gapBefore gapAfter textWidth
                            lineDef linFilePath point currentY safeStr numLines separator linesToLoad 
                            oldExpert linFileName fLin)
    (vl-load-com)
    (setvar "CMDECHO" 0)
    (setq numLines 0)
    (setq linesToLoad '()) 

    ;; -------------------------------------------------------------------------
    ;; 1. CAU HINH THONG SO DE (User co the sua o day)
    ;; -------------------------------------------------------------------------
    (setq textHeight 0.2)   ;; Chieu cao chu co dinh (nho de khong bi tho)
    (setq yOffset -0.1)     ;; Can giua theo chieu doc (= -1/2 chieu cao)
    (setq dashLength 3.0)   ;; Do dai doan gach (3m)
    (setq gapBefore -0.2)   ;; Khoang ho truoc chu (0.2m)
    
    ;; -------------------------------------------------------------------------
    ;; 2. CHON FILE VA THU MUC
    ;; -------------------------------------------------------------------------
    (setq csvFile (getfiled "Chon file danh sach Line (CSV/TXT)" "" "csv;txt" 16))
    (if (not csvFile) (progn (princ "\nDa huy chon file.") (exit)))
    
    (setq separator (getstring T "\nNhap ky tu phan cach giua Line Type va Description (vi du: ',' hoac ';'): "))
    (if (or (not separator) (equal separator "")) (progn (princ "\nChua nhap ky tu phan cach.") (exit)))
    
    (setq outputFolder (GetFolder "Chon thu muc de luu CAC file .lin rieng biet"))
    (if (not outputFolder) (progn (princ "\nDa huy chon thu muc.") (exit)))
    
    ;; Tao Layer
    (if (not (tblsearch "LAYER" "DZ_hathe")) (command "._LAYER" "N" "DZ_hathe" "C" 4 "DZ_hathe" ""))
    (setvar "CLAYER" "DZ_hathe") 
    
    (princ "\nDang xu ly du lieu...")
    (setq fDat (open csvFile "r"))
    
    (if fDat
        (progn
            ;; -----------------------------------------------------------------
            ;; 3. TAO FILE .LIN VOI CONG THUC TINH KHOANG CACH DONG
            ;; -----------------------------------------------------------------
            (while (setq lineStr (read-line fDat))
                (setq safeStr (vl-string-translate "\"" " " lineStr))
                (setq lineList (SplitStr safeStr separator)) 
                (setq lineType (car lineList)) 
                
                (if lineType
                    (progn
                        (setq lineType (vl-string-trim " " lineType))
                        (if (> (strlen lineType) 0)
                            (progn
                                (setq lineDesc (if (cadr lineList) (cadr lineList) lineType))
                                
                                ;; --- TINH TOAN KHOANG HO SAU CHU (Auto fit) ---
                                ;; Uoc luong be rong chu = So ky tu * Chieu cao * He so (1.0 cho font Standard)
                                ;; Them 0.2 la khoang dem an toan
                                (setq textWidth (* (strlen lineType) textHeight 1.0))
                                (setq gapAfter (* -1.0 (+ textWidth 0.2)))
                                
                                ;; Tao ten file an toan
                                (setq linFileName (vl-string-translate "/\\*?:<>|\"" "________" lineType)) 
                                (setq linFileName (strcat linFileName ".lin"))
                                (setq linFilePath (strcat outputFolder linFileName))
                                
                                ;; Ghi file
                                (setq fLin (open linFilePath "w"))
                                (write-line (strcat "*" lineType "," lineDesc) fLin)
                                
                                ;; Format: A, Dash, GapBefore, [TEXT], GapAfter
                                ;; GapAfter chiu trach nhiem day but ve phia sau het chieu dai chu
                                (setq lineDef 
                                    (strcat "A," 
                                            (rtos dashLength 2 2) "," 
                                            (rtos gapBefore 2 2) "," 
                                            "[\"" lineType "\",Standard,y=" (rtos yOffset 2 2) ",s=" (rtos textHeight 2 2) ",u=0],"
                                            (rtos gapAfter 2 2)
                                    )
                                )
                                (write-line lineDef fLin)
                                (close fLin)
                                
                                (setq linesToLoad (append linesToLoad (list linFilePath)))
                                (setq numLines (1+ numLines))
                            )
                        )
                    )
                )
            )
            (close fDat)
            (princ (strcat "\nDa tao xong " (itoa numLines) " file .lin. Dang Load vao CAD..."))
            
            ;; -----------------------------------------------------------------
            ;; 4. LOAD LINETYPE (SUA LOI KHONG TIM THAY FILE)
            ;; -----------------------------------------------------------------
            (setq oldExpert (getvar "EXPERT"))
            (setvar "EXPERT" 3) ;; Tu dong ghi de khong hoi nhieu
            
            (setq numLines 0)
            (foreach linPath linesToLoad
                ;; Cu phap dung: ._LINETYPE -> _Load -> * -> Path
                (command "._LINETYPE" "_L" "*" linPath "")
                (setq numLines (1+ numLines))
            )
            (setvar "EXPERT" oldExpert)
            (princ (strcat "\nDa Load " (itoa numLines) " Linetype."))

            ;; -----------------------------------------------------------------
            ;; 5. VE MAU THU
            ;; -----------------------------------------------------------------
            (princ "\nChon diem bat dau de ve danh sach Line mau...")
            (setq point (getpoint "\nChon diem bat dau:"))
            
            (if point
                (progn
                    (setq currentY (cadr point))
                    (setq fDat (open csvFile "r"))
                    (setq numLines 0)
                    
                    (while (setq lineStr (read-line fDat))
                        (setq safeStr (vl-string-translate "\"" " " lineStr))
                        (setq lineList (SplitStr safeStr separator))
                        (setq lineType (car lineList))
                        
                        (if lineType
                            (progn
                                (setq lineType (vl-string-trim " " lineType))
                                (if (and (> (strlen lineType) 0) (tblsearch "LTYPE" lineType))
                                    (progn
                                        (entmake
                                            (list
                                                '(0 . "LINE") (cons 8 "DZ_hathe")
                                                (cons 6 lineType) (cons 48 1.0) (cons 62 4) 
                                                (cons 10 (list (car point) currentY 0.0))       
                                                (cons 11 (list (+ (car point) 30.0) currentY 0.0)) ;; Ve dai 30m de test
                                            )
                                        )
                                        (setq currentY (- currentY 2.0)) ;; Giam khoang cach dong xuong cho gon
                                        (setq numLines (1+ numLines))
                                    )
                                )
                            )
                        )
                    )
                    (close fDat)
                    (princ (strcat "\nHoan thanh! Da ve " (itoa numLines) " duong line."))
                )
            )
        )
        (princ "\nLoi: Khong the doc file CSV.")
    )
    (setvar "CMDECHO" 1)
    (princ)
)
