#! /bin/env tclsh

package require {ycl test}

proc suite_main {} {
	package require {ycl file signature}
	namespace import [yclprefix]::file::signature
	package require {ycl dir}
	namespace import [yclprefix]::dir
	package require {ycl list}
	namespace import [yclprefix]::test::cleanup1
	package require {ycl flow file}
	package require {ycl flow routine}
	namespace import [yclprefix]::flow
	package require {ycl flow util}
	namespace import [yclprefix]::flow::util
	namespace import [yclprefix]::list::sl
	package require {ycl test data}

	set setup1 {
		set tempdir [dir mktempdir]
		cd $tempdir
	}

	[yclprefix]::test::init

	variable cleanup2 {}
	set cleanup2 "file delete -force \$tempdir\n[cleanup1]"

	test routine {} -setup $setup1 -body {
		variable a
		variable b 0
		variable c
		coroutine b1 if 1 {
			yield [info coroutine]
			yield 2
			yield 2
			yield 4
		}
		[flow routine spawn a] init prereq b script {
			variable a
			variable c
			lappend c {making a}
			set a 3
		}

		proc b args {
			variable b
			variable c
			set oldb $b
			set b [b1]
			lappend c {making b}
			if {$oldb != $b} {
				return [info cmdcount]
			}
			return 0
		}

		trace add variable a read [list apply [list args {
			a make
		} [namespace current]]]
		return [list $a $a $a $b $c]
	} -cleanup $cleanup2 -result [sl {
		3 3 3 4 
		[list {making b} {making a} {making b} {making b} {making a}]
	}]

	test file {} -setup $setup1 -body {
		variable b
		proc maker0 name {
			variable b
			lappend b [list making $name]
			set chan [open $name a+]
			puts $chan data1
			close $chan
			return [info cmdcount] 
		}
		coroutine maker1 ::apply [list {} {
			set name [yield [info cmdcount]]
			set name [yield [maker0 $name]]
			set name [yield 0]
			set name [yield [maker0 $name]]
		} [namespace current]]

		proc maker2 name {
			variable b
			lappend b [list making $name]
			set chan [open a.tmpl]
			set data [string trim [read $chan]]
			close $chan
			set chan [open $name a+]
			puts -nonewline $chan $data$data 
			close $chan
		}

		[flow file spawn file1] init script {maker1 a.tmpl} \
			target a.tmpl
		[flow file spawn file2] init prereq {file1 make} \
			script {maker2 a.txt} target a.txt

		file2 make
		file2 make
		file2 make
		set chan [open a.txt]
		set res [read $chan]
		close $chan
		lappend res $b
		return $res
	} -cleanup $cleanup2 -result [sl {
		data1data1
		{{making a.tmpl} {making a.txt}}
	}]

	if 0 {

	#works in progress
	test file_auto {} -setup $setup1 -body {
		proc maketxt {name} {
			set chan [open $name a+]
			puts $chan madetxt
			close $chan
		}
		flow file spawn file1
		set chan [open a.txt]
	} -cleanup $cleanup2 -result [sl {
		yada
	}]

	if 0 {
		test pattern {} -setup $setup1 -body {
			set chan [open a.c w]
			puts $chan {int main ()}
			close $chan
			file a
			a run
			set chan [open a]
			set res [read $chan]
			close $chan
			return $res
		} -cleanup [cleanup1] -result [sl {
			data1data1
		}]
	}

	} ;# if 0



	cleanupTests
}
