#!/usr/bin/newlisp

;; qa-utf16path - check WIN_32 file and directory routines on 
;; UTF-16 encoded paths

;; run with N = 10000 to check for memory leaks
;; ./qa-utf16path 10000
;; newlisp qa-utf16path 10000


(println)
(println "Testing UTF-16 path names")

(if (main-args 2)
	(setq N (int (main-args 2)))
	(setq N 10))

(when (= 0 (& (sys-info -1) 128))
		(println ">>>>> qa-utf16path: This test is only used on UTF8 enabled versions.")
		(exit)
)

(set 'Yuki "\230\162\182\230\181\166\231\148\177\232\168\152")
(set 'InvalidUTF8 "\xC0\xC1")

(set 'UnicodeStr Yuki)

(set 'h 1) ; pre allocate mem so changes should be minimal
(set 'sRand 
	(join (map char (map (curry + 32)
		(rand 
			(- 127 32)
			(+ 10 90);(rand 100))
		)
	)
)))
(set 'buff sRand)


(define-macro (assert any)
	(local (result)
		(when (not (set 'result (eval any)))
			(println (string " >>>> Expression failed! " any))
			(setq fail true)
			(if (> N 10) (exit))
		)
		result
	)
)


(println "Step 1:")

(println (time 
	(begin 
		(assert (make-dir UnicodeStr))
		(assert (remove-dir UnicodeStr))
	)
	N	
))

(println "Step 2:")

(assert (make-dir UnicodeStr))
(println (time (assert (directory? UnicodeStr)) N))
(println (time (assert (file? UnicodeStr)) N))
(println (time (begin
	(assert (directory))
	(assert (directory "." UnicodeStr))
	(assert (= 1 (length (directory "." UnicodeStr))))
	(assert (real-path UnicodeStr))
	(assert (change-dir UnicodeStr))
	(assert (real-path))
	(assert (directory))
	(assert (change-dir ".."))
) N))
(assert (remove-dir UnicodeStr))

(println "Step 3:")
		
(println (time
	(begin
		(assert (write-file UnicodeStr sRand))
		(assert (= (read-file UnicodeStr) sRand))
		(assert (append-file UnicodeStr (reverse sRand)))
		(assert (delete-file UnicodeStr))
	)
N ))

(println "Step 4:")

(assert (write-file UnicodeStr sRand))

(println (time (assert (not (directory? UnicodeStr))) N))
(println (time (assert (file? UnicodeStr)) N))

(println (time (assert (file-info UnicodeStr)) N))

(println "Step 5:")

(println (time (begin
	(assert (set 'h (open UnicodeStr "w")))
	(assert (write-buffer h sRand))
	(assert (close h))
	(assert (set 'h (open UnicodeStr "a")))
	(assert (write-buffer h (reverse sRand)))
	(assert (close h))
	(assert (set 'h (open UnicodeStr "r")))
	(assert (read-buffer h buff 1024))
	(assert (close h))
	(assert (rename-file UnicodeStr "foo"))
	(assert (rename-file "foo" UnicodeStr))
	(assert (rename-file UnicodeStr UnicodeStr))
	(when (find ostype '("Windows" "Cygwin"))
		(assert (not (rename-file UnicodeStr InvalidUTF8)))
		(assert (not (rename-file InvalidUTF8 InvalidUTF8)))
		(assert (not (rename-file InvalidUTF8 UnicodeStr)))
	)
) N))

(assert (delete-file UnicodeStr))

(println "Step 6:")

(println (time (save UnicodeStr) N))

(assert (delete-file UnicodeStr))

(if-not fail
	(println ">>>>> UTF-16 path-file-names testing SUCCESSFUL")
	(println ">>>>> PROBLEM with UTF-16 path-file-names processing")
)

(exit)

