// mac_sandbox_test.go v1.0

package sandbox

import (
	"fmt"
	"strings"
	"sync"
	"testing"
	"time"

	"apigo.cc/gojs"
	_ "apigo.cc/gojs/console"
	_ "apigo.cc/gojs/file"
	_ "apigo.cc/gojs/runtime"

	_ "apigo.cc/gojs/util"
	"github.com/ssgo/u"
)

func init() {
	gojs.Register("testTool", gojs.Module{
		Object: map[string]interface{}{
			"runAll": func(tasks [][]any) []any {
				res := make([]any, len(tasks))
				var wg sync.WaitGroup
				for i, taskArgs := range tasks {
					wg.Add(1)
					go func(index int, args []any) {
						defer wg.Done()
						script := u.String(args[0])
						if !strings.ContainsRune(script, '\n') && u.FileExists(script) {
							r, err := gojs.RunFile(script, args[1:]...)
							res[index] = []any{r, err}
						} else {
							r, err := gojs.Run(script, "anonymous.js", args[1:]...)
							res[index] = []any{r, err}
						}
					}(i, taskArgs)
				}
				wg.Wait()
				return res
			},
		},
	})
}

func TestPlugin(t *testing.T) {
	tests := []string{
		"base_test.js",
		// "nodejs_test.js",
	}

	gojs.ExportForDev()
	for _, f := range tests {
		r, err := gojs.RunFile(f)
		if err != nil {
			t.Fatal(u.Red(f), u.BRed(err.Error()))
		} else if r != true {
			t.Fatal(u.Red(f), u.BRed(u.JsonP(r)))
		} else {
			fmt.Println(u.Green(f), u.BGreen("test succeess"))
		}
	}

	time.Sleep(500 * time.Millisecond)
}
