;;; WCS CSV point import command.
;;; SPDX-License-Identifier: GPL-3.0-or-later

(defun C:CTIMPORT (/ *error* document file handle header x-index y-index z-index line row x y z layer created skipped)
  (defun *error* (message)
    (if handle (progn (close handle) (setq handle nil)))
    (ACT:report-error message document)
  )
  (setq document (ACT:undo-start))
  (setq file (getfiled "Import ACT CSV (WCS)" "" "csv" 0))
  (cond
    ((not file) (ACT:message "Import was cancelled."))
    ((not (setq handle (open file "r"))) (ACT:message "Unable to read the selected file."))
    ((not (setq header (ACT:csv-parse-line (read-line handle))))
      (close handle)
      (setq handle nil)
      (ACT:message "CSV header is invalid."))
    (T
      (setq x-index (ACT:header-index "x" header)
            y-index (ACT:header-index "y" header)
            z-index (ACT:header-index "z" header))
      (if (or (not (numberp x-index)) (not (numberp y-index)) (not (numberp z-index)))
        (ACT:message "CSV must contain x, y, and z header columns.")
        (progn
          (setq layer (ACT:ensure-layer "ACT-IMPORT" 2) created 0 skipped 0)
          (while (setq line (read-line handle))
            (setq row (ACT:csv-parse-line line))
            (if row
              (setq x (ACT:parse-number (ACT:nth-safe x-index row))
                    y (ACT:parse-number (ACT:nth-safe y-index row))
                    z (ACT:parse-number (ACT:nth-safe z-index row)))
              (setq x nil y nil z nil)
            )
            (if (and (numberp x) (numberp y) (numberp z) (ACT:make-point (list x y z) layer))
              (setq created (1+ created))
              (setq skipped (1+ skipped))
            )
          )
          (ACT:message (strcat "Imported " (itoa created) " WCS points; skipped " (itoa skipped) " rows."))
        )
      )
      (close handle)
      (setq handle nil)
    )
  )
  (ACT:undo-end document)
  (setq document nil)
  (princ)
)

(princ)
