;;; ------------------------------------------------------------
;;; AutoCATS ¸®½À ÀÚ·á½Ç
;; ¸í·É: LAYERRESET
;; ±â´É: ÆíÁý °¡´ÉÇÑ ·¹ÀÌ¾î¸¦ ¸ðµÎ ÄÑ°í µ¿°á ¹× Àá±Ý ÇØÁ¦
;; ÃâÃ³: https://www.autocats.co.kr/lisp/layer-reset
;; ¹öÀü: 1.0 (2026-07-23)
;; ¶óÀÌ¼±½º: ÀÚÀ¯ »ç¿ë¡¤¼öÁ¤, Àç¹èÆ÷ ½Ã ÃâÃ³(autocats.co.kr) Ç¥±â
;; ¾ÈÀü: *error* ÇÚµé·¯ + UNDO ±×·ì, Xref Á¾¼Ó ·¹ÀÌ¾î °Ç³Ê¶Ü
;;; ------------------------------------------------------------

(defun autocats-layerreset-xref-p (name)
  (if (vl-string-search "|" name) T nil))

(defun autocats-layerreset-one (name / result)
  (setq result
        (vl-catch-all-apply
          '(lambda ()
             (command "_.-LAYER" "_On" name "")
             (command "_.-LAYER" "_Thaw" name "")
             (command "_.-LAYER" "_Unlock" name "")
             T)))
  (if (vl-catch-all-error-p result) nil result))

(defun autocats-layerreset-run (/ row name changed skipped)
  (setq changed 0 skipped 0
        row (tblnext "LAYER" T))
  (while row
    (setq name (cdr (assoc 2 row)))
    (if (or (autocats-layerreset-xref-p name)
            (not (autocats-layerreset-one name)))
      (setq skipped (1+ skipped))
      (setq changed (1+ changed)))
    (setq row (tblnext "LAYER")))
  (cons changed skipped))

(defun c:LAYERRESET (/ *error* undo-open result)
  (defun *error* (msg)
    (if undo-open
      (progn (command "_.UNDO" "_End") (setq undo-open nil)))
    (if (and msg (not (wcmatch (strcase msg) "*CANCEL*,*QUIT*,*EXIT*,*Ãë¼Ò*")))
      (princ (strcat "\n[LAYERRESET] Áß´Ü: " msg)))
    (princ))

  (command "_.UNDO" "_Begin")
  (setq undo-open T
        result (autocats-layerreset-run))
  (command "_.UNDO" "_End")
  (setq undo-open nil)
  (princ (strcat "\n[LAYERRESET] ¿Ï·á: " (itoa (car result))
                 "°³ ·¹ÀÌ¾î º¹¿ø / " (itoa (cdr result)) "°³ °Ç³Ê¶Ü"))
  (princ))

(princ "\n[AutoCATS] LAYERRESET ·Îµå ¿Ï·á - ¸í·ÉÇà¿¡ LAYERRESET ¸¦ ÀÔ·ÂÇÏ¼¼¿ä.")
(princ)
