;; DailyPainkiller CREATETOOLS v0.2 - Myo Myint Maung x OpenAI
(vl-load-com)

(defun CRT:ask (message / k)
  (initget "Yes No")
  (= "Yes" (getkword (strcat "\n" message " [Yes/No] <No>: "))))

(defun CRT:space ()
  (list (cons 410 (if (= 1 (getvar "CVPORT")) (getvar "CTAB") "Model"))))

(defun CRT:list (ss / i out)
  (if ss (repeat (setq i (sslength ss))
    (setq out (cons (ssname ss (setq i (1- i))) out)))) (reverse out))

(defun CRT:pickset (lst / ss e)
  (setq ss (ssadd)) (foreach e lst (if (entget e) (ssadd e ss))) ss)

(defun CRT:scope (filter / k)
  (initget "Select Current")
  (setq k (getkword "\nScope [Select/Current] <Select>: "))
  (if (= k "Current") (ssget "_X" (append filter (CRT:space)))
    (progn (princ "\nSelect objects: ") (ssget filter))))

(defun CRT:writeable (e / lay)
  (setq lay (tblsearch "LAYER" (cdr (assoc 8 (entget e)))))
  (and lay (= 0 (logand 4 (cdr (assoc 70 lay))))
    (vlax-write-enabled-p (vlax-ename->vla-object e))))

(defun CRT:positive (msg fallback / v)
  (initget 6) (setq v (getreal (strcat "\n" msg " <" (rtos fallback 2 3) ">: ")))
  (if v v fallback))

(defun CRT:areas (/ ss units factor height precision space doc e obj area point text result ok failed)
  (setq ss (ssget '((0 . "HATCH"))))
  (if ss
    (progn
      (initget 1 "Millimetres Metres Feet Inches")
      (setq units (getkword "\nDrawing length units [Millimetres/Metres/Feet/Inches]: "))
      (setq factor (cond ((= units "Millimetres") 0.000001) ((= units "Feet") 0.09290304)
        ((= units "Inches") 0.00064516) (t 1.0)))
      (setq height (CRT:positive "Text height in drawing units" (getvar "TEXTSIZE")))
      (initget 4) (setq precision (getint "\nDecimal places 0-8 <2>: "))
      (if (or (null precision) (> precision 8)) (setq precision 2))
      (setq doc (vla-get-activedocument (vlax-get-acad-object))
        space (if (= 1 (getvar "CVPORT")) (vla-get-paperspace doc) (vla-get-modelspace doc)) ok 0 failed 0)
      (princ "\nLabels are static snapshots. Pick each label location; Enter skips that hatch.")
      (foreach e (CRT:list ss)
        (setq obj (vlax-ename->vla-object e) area (vl-catch-all-apply 'vla-get-area (list obj)))
        (if (vl-catch-all-error-p area) (setq failed (1+ failed))
          (progn
            (sssetfirst nil (CRT:pickset (list e)))
            (setq point (getpoint (strcat "\nArea " (rtos (* area factor) 2 precision) " m2; label location: ")))
            (if point
              (progn
                (setq result (vl-catch-all-apply 'vla-addtext
                  (list space (strcat (rtos (* area factor) 2 precision) " m2")
                    (vlax-3d-point (trans point 1 0)) height)))
                (if (vl-catch-all-error-p result) (setq failed (1+ failed))
                  (progn (vla-put-layer result (getvar "CLAYER"))
                    (vla-put-stylename result (getvar "TEXTSTYLE")) (setq ok (1+ ok)))))))))
      (princ (strcat "\nLabels created: " (itoa ok) "; failures: " (itoa failed))))))

(defun CRT:linetype (/ name text style h dash gap pattern path f line doc r)
  (setq name (strcase (getstring T "\nLinetype name (letters/numbers/underscore): ")))
  (if (and (/= name "") (not (wcmatch name "*[~A-Z0-9_]*")))
    (progn
      (setq text (getstring T "\nService text, e.g. CHWS: ") style (getvar "TEXTSTYLE"))
      (if (and (/= text "")
               (not (vl-some '(lambda (c) (member c '(34 92 44 91 93 10 13))) (vl-string->list text)))
               (not (vl-some '(lambda (c) (member c '(34 44 91 93 10 13))) (vl-string->list style))))
        (progn
          (setq h (CRT:positive "Text height (use a zero-height text style)" 2.5)
            dash (CRT:positive "Dash length" 12.0)
            gap (CRT:positive "Text space (increase for longer words)" (* h (+ 2 (strlen text)))))
          (initget "Dash Dot DashDot")
          (setq pattern (getkword "\nPattern [Dash/Dot/DashDot] <Dash>: "))
          (setq line (strcat "A," (if (= pattern "Dot") "0" (rtos dash 2 6))
            ",-" (rtos h 2 6) (if (= pattern "DashDot") (strcat ",0,-" (rtos h 2 6)) "")
            ",[\"" text "\"," style ",S=" (rtos h 2 6) ",U=0.0,X=0.0,Y="
            (rtos (* -0.5 h) 2 6) "],-" (rtos gap 2 6)))
          (princ (strcat "\nDefinition: " line))
          (setq path (getfiled "Save NEW LIN file (existing file will be replaced)" (strcat name ".lin") "lin" 1))
          (if (and path (or (not (findfile path)) (CRT:ask "Replace the entire existing LIN file?")))
            (progn
              (setq f (open path "w"))
              (if f
                (progn (write-line (strcat "*" name ",DailyPainkiller " text) f) (write-line line f) (close f)
                  (princ "\nLIN file saved. This file write is not reversed by drawing UNDO.")
                  (if (tblsearch "LTYPE" name)
                    (princ "\nName already loaded: use LINETYPE to reload deliberately.")
                    (if (CRT:ask "Load this linetype into the current drawing?")
                      (progn
                        (setq doc (vla-get-activedocument (vlax-get-acad-object))
                          r (vl-catch-all-apply 'vla-load (list (vla-get-linetypes doc) name path)))
                        (if (vl-catch-all-error-p r) (princ (strcat "\nLoad failed: " (vl-catch-all-error-message r)))
                          (princ "\nLoaded. Test on a line and adjust LTSCALE/text space as needed."))))))
                (princ "\nUnable to write LIN file.")))))
        (princ "\nInvalid/empty text or unsupported punctuation in text/style.")))
    (princ "\nInvalid name.")))

(defun c:CREATETOOLS (/ *error* doc echo undo choice)
  (setq doc (vla-get-activedocument (vlax-get-acad-object)) echo (getvar "CMDECHO"))
  (defun *error* (msg)
    (if undo (vl-catch-all-apply 'vla-endundomark (list doc)))
    (setvar "CMDECHO" echo)
    (if (and msg (not (wcmatch (strcase msg) "*CANCEL*,*QUIT*,*BREAK*")))
      (princ (strcat "\nStopped: " msg)))
    (princ "\nCompleted edits may remain; use UNDO if needed.") (princ))
  (princ "\nCREATETOOLS: 1 Create service text linetype | 2 Label hatch areas")
  (initget 6) (setq choice (getint "\nChoose [1-2] <exit>: "))
  (if (member choice '(1 2))
    (progn
      (vla-startundomark doc) (setq undo T) (setvar "CMDECHO" 0)
      (cond ((= choice 1) (CRT:linetype)) ((= choice 2) (CRT:areas)))
      (vla-endundomark doc) (setq undo nil) (setvar "CMDECHO" echo)))
  (princ))
(princ "\nCREATETOOLS v0.2 loaded. Type CREATETOOLS.")
(princ)
