;;; ------------------------------------------------------------
;;; AutoCATS ¸®½À ÀÚ·á½Ç
;; ¸í·É: HAREA
;; ±â´É: ¼±ÅÃÇÑ HATCH °´Ã¼ÀÇ ¸éÀû ÇÕ°è °è»ê + µµ¸é ±âÀÔ(¼±ÅÃ)
;; ÃâÃ³: https://www.autocats.co.kr/lisp/hatch-area
;; ¹öÀü: 1.0 (2026-07-23)
;; ¶óÀÌ¼±½º: ÀÚÀ¯ »ç¿ë¡¤¼öÁ¤, Àç¹èÆ÷ ½Ã ÃâÃ³(autocats.co.kr) Ç¥±â
;; ¾ÈÀü: *error* ÇÚµé·¯ + UNDO ±×·ì, ¿øº» ÇØÄ¡ ¼öÁ¤ ¾øÀ½
;;; ------------------------------------------------------------

(vl-load-com)

(defun autocats-harea-value (ent / result)
  (setq result
        (vl-catch-all-apply
          '(lambda ()
             (command "_.AREA" "_Object" ent)
             (getvar "AREA"))))
  (if (vl-catch-all-error-p result) nil result))

(defun autocats-harea-text (point value precision / wcs)
  (setq wcs (trans point 1 0))
  (entmakex
    (list
      (cons 0 "TEXT")
      (cons 10 wcs)
      (cons 40 (getvar "TEXTSIZE"))
      (cons 1 (rtos value 2 precision))
      (cons 7 (getvar "TEXTSTYLE")))))

(defun c:HAREA (/ *error* doc undo-open ss idx ent value total counted skipped precision answer point)
  (defun *error* (msg)
    (if undo-open
      (progn (vla-EndUndoMark doc) (setq undo-open nil)))
    (if (and msg (not (wcmatch (strcase msg) "*CANCEL*,*QUIT*,*EXIT*,*Ãë¼Ò*")))
      (princ (strcat "\n[HAREA] Áß´Ü: " msg)))
    (princ))

  (princ "\n[HAREA] ¸éÀûÀ» ÇÕ»êÇÒ HATCH °´Ã¼¸¦ ¼±ÅÃÇÏ¼¼¿ä.")
  (setq ss (ssget '((0 . "HATCH"))))
  (if ss
    (progn
      (setq total 0.0 counted 0 skipped 0 idx 0
            precision (getvar "DIMDEC"))
      (while (< idx (sslength ss))
        (setq ent (ssname ss idx)
              value (autocats-harea-value ent))
        (if value
          (setq total (+ total value) counted (1+ counted))
          (setq skipped (1+ skipped)))
        (setq idx (1+ idx)))
      (princ (strcat "\n[HAREA] ¸éÀû ÇÕ°è: " (rtos total 2 precision)
                     "  (ÇÕ»ê " (itoa counted) "°³ / °Ç³Ê¶Ü " (itoa skipped)
                     "°³, ÇöÀç µµ¸é ´ÜÀ§ ±âÁØ)"))
      (if (> counted 0)
        (progn
          (initget "Y N")
          (setq answer
                (getkword "\nÇÕ°è¸¦ µµ¸é¿¡ ¹®ÀÚ·Î ±âÀÔÇÒ±î¿ä? [¿¹(Y)/¾Æ´Ï¿À(N)] <N>: "))
          (if (= answer "Y")
            (progn
              (setq point (getpoint "\n¹®ÀÚ »ðÀÔ À§Ä¡: "))
              (if point
                (progn
                  (setq doc (vla-get-ActiveDocument (vlax-get-acad-object)))
                  (vla-StartUndoMark doc)
                  (setq undo-open T)
                  (autocats-harea-text point total precision)
                  (vla-EndUndoMark doc)
                  (setq undo-open nil))))))))
    (princ "\n[HAREA] ¼±ÅÃµÈ ÇØÄ¡°¡ ¾ø½À´Ï´Ù."))
  (princ))

(princ "\n[AutoCATS] HAREA ·Îµå ¿Ï·á - ¸í·ÉÇà¿¡ HAREA ¸¦ ÀÔ·ÂÇÏ¼¼¿ä.")
(princ)
