;;;
;;; Phab Language support
;;;

(defclass Translation nil nil
  (widgetname
   resnum
   resname
   dummy1
   dummy2
   font
   deflength
   default
   trans_alist
   ))

(defun PhabReadLangDB (filename)
  (let (translist fptr)
    (if (setq fptr (open filename "r"))
	(let (line inst)
	  (read_line fptr)		; swallow Phab version
	  (while (not (eq (setq line (read_line fptr)) _eof_))
	    (setq line (list_to_array (string_split line "," 8)))
	    (setq inst (new Translation))
	    (-> inst widgetname (symbol (aref line 0)))
	    (-> inst resnum (number (aref line 1)))
	    (-> inst resname (aref line 2))
	    (-> inst dummy1 (number (aref line 3)))
	    (-> inst dummy2 (number (aref line 4)))
	    (-> inst font (aref line 5))
	    (-> inst deflength (number (aref line 6)))
	    (if (= (@ inst deflength) 0)
		(-> inst default (aref line 7))
	      (-> inst default
		  (buffer_to_string (read_n_chars fptr (@ inst deflength))))
	      )
	    (setq translist (cons inst translist))
	    )
	  (close fptr)
	  )
      )
    (reverse translist)
    )
  )

(defun TransFindMember (translist widgetname resnum)
  (let (found trans)
    (while (and translist (not found))
      (setq trans (car translist))
      (if (and (eq (@ trans widgetname) widgetname)
	       (= (@ trans resnum) resnum))
	  (setq found trans))
      (setq translist (cdr translist))
      )
    found
    )
  )

(defun PhabReadTranslationFile (filename translist)
  (let (fptr lang_suffix)
    (if (setq fptr (open filename "r"))
	(let (line trans_string len trans)
	  (setq lang_suffix (string_split filename "." 0))
	  (setq lang_suffix (car (nth_cdr lang_suffix
					  (- (length lang_suffix) 1))))
	  (while (not (eq (setq line (read_line fptr)) _eof_))
	    (setq line (list_to_array (string_split line "," 6)))
	    (setq len (number (aref line 4)))
	    (if (= len 0)
		(setq trans_string (aref line 5))
	      (progn
		(setq trans_string (buffer_to_string
				    (read_n_chars fptr len)))
		)
	      )
	    (if (setq trans (TransFindMember translist (symbol (aref line 0))
					     (number (aref line 1))))
		(progn
		  (if (setq existing (car (assoc_equal lang_suffix
						       (@ trans trans_alist))))
		      (rplacd existing trans_string)
		    (-> trans trans_alist (cons (cons lang_suffix trans_string)
						(@ trans trans_alist)))
		    )
		  )
	      (princ "No translation for " (aref line 0) ", res "
		     (aref line 1) "\n")
	      )
	    )
	  (close fptr)
	  )
      (princ "Could not open language file " filename "\n")
      )
    )
  )

(defun PhabApplyLanguage (translist langname)
  (let (widget langstr)
    (for trans in translist do
	 (if (not (undefined_p (setq widget (eval (@ trans widgetname)))))
	     (progn
	       (setq langstr (cdar (assoc_equal langname
						(@ trans trans_alist))))
	       (if (not langstr)
		   (setq langstr (@ trans default)))
	       (:-> widget (PtResourceName widget (@ trans resnum)) langstr)
	       )
	   )
	 )
    )
  )
