package main

import (
	"reflect"
	"strings"
	"syscall/js"
	"time"

	"Toolbox/goDataverseStrict/metrics"

	"git.archium.org/archium_public/ebkTools/wasm"
	archiumwasm "git.archium.org/archium_public/ebkTools/wasm"
	//_ nwa "git.archium.org/archium_public/ebkTools/nhooyrioWebsocketAddons"
	//"Toolbox/goDataverseStrict/metrics"
)

// Setze und lese aus ID
const (
	//ENHANCErecords = false
	//ENHANCEebenen  = false
	DEBUG         = true
	LOOPTAKT      = "0.6s"                    //Kontschi sagt "0.7s"
	PDPURL        = "https://pdp.archium.org" //"http://localhost:8080"
	SPANSEPARATOR = "bis"
)

/*
var signal = make(chan int)

func keepAlive() {
	for {
		<-signal
	}
}
*/

func getIdWhichJustChanged() func(js.Value, []metrics.OneJumpPointSet) (string, int8) {
	var oldIds, newIds []wasm.Checkerboard

	internalClosureFunction := func(injectpoint js.Value, ojpsdata []metrics.OneJumpPointSet) (string, int8) {
		var founditS string
		var founditI int8 = -1 //Default

		var tmpIdsS []string
		var tmpIdsI []int8

		for l := int8(0); l <= 3; l++ {
			a, _ := metrics.FilterStacklist(ojpsdata, l)

			for _, v := range a {
				tmpIdsS = append(tmpIdsS, metrics.IDRequestCriteriaPrefix+v)
				tmpIdsI = append(tmpIdsI, l)
			}
		}

		//log.Println(tmpIdsS)
		newIds = wasm.GetStatusFromBulkOfIds(injectpoint, tmpIdsS)

		if len(oldIds) > 0 && !reflect.DeepEqual(oldIds, newIds) {
			for i, n := range newIds {
				if oldIds[i].Checked != n.Checked && !oldIds[i].Checked && n.Checked { //newIds[i].Checked
					founditS = strings.TrimPrefix(n.Id, metrics.IDRequestCriteriaPrefix)
					founditI = tmpIdsI[i]
					break
				}
			}

		}
		oldIds = newIds

		return founditS, founditI

	}
	return internalClosureFunction
}

func barseTuration(s string) time.Duration {
	d, err := time.ParseDuration(s)
	if err != nil {
		panic(err)
	}
	return d
}

func main() {

	var (
		dombase, bodyInject, scriptarea, chartarea, submitbutton js.Value
		//dombase, body, body2, butt, , bodyDatabase, bodyTectonics,  js.Value

		/*TODO: 		WICHTIG nicht löschen
		oldcheckers, newcheckers                      []archiumwasm.Checkerboard
		checked_type, oldchecked_type, checked_result string
		*/
	)

	closureGetIdWhichJustChanged := getIdWhichJustChanged()

	//log.Println("started")

	//connectionReceive, _, errReceive := websocket.Dial(ctx, "ws://"+configs["websockeIp"]+":"+configs["websocketPort0S"], nil)
	//connectionSend, _, errSend := websocket.Dial(ctx, "ws://"+configs["websockeIp"]+":"+configs["websocketPort1R"], nil)

	dombase = js.Global().Get("document")

	//bodyDatabase = dombase.Call("getElementById", vectorIdDatabase) //.Index(0)
	//bodyTectonics = dombase.Call("getElementById", vectorIdDescription)
	bodyInject = dombase.Call(wasm.DOCUMENTS_METHOD_getElementById, "injectarea")
	scriptarea = dombase.Call(wasm.DOCUMENTS_METHOD_getElementById, "scriptarea")
	//formarea = dombase.Call("getElementById", "formarea")
	//testarea = dombase.Call(wasm.DOCUMENTS_METHOD_getElementById, "testarea")

	chartarea = dombase.Call(archiumwasm.DOCUMENTS_METHOD_getElementById, "chartarea")
	submitbutton = dombase.Call(archiumwasm.DOCUMENTS_METHOD_getElementById, metrics.IDFormSubmit)

	var oldPseudoSubmitData, pseudoSubmitData lokalRequestType

	//butt = dombase.Call("getElementById", "runButton")
	//lmog.Println(butt)

	//	tmpRohtext := bodyDatabase.Get("innerText").String()
	//tmpRohtextTectonics := bodyTectonics.Get("innerText").String()

	//bodyInject.Set("innerText", fmt.Sprintf("%v", os.Args))

	if DEBUG { // Zeige Pinguin als Zeichen dafür, daß das Programm vollständig durchlaufen wurde
		image := dombase.Call("createElement", "img")
		image.Set("src", "data:image/png;base64,"+imageByteArrayAsBase64)
		bodyInject.Call("appendChild", image)
	}

	//image2 := dombase.Call("createElement", "img")
	//image2.Set("src", "data:image/png;base64,"+imageByteArrayAsBase64)
	//body2.Call("appendChild", image)

	//js.Global().Get("console").Call("log", "Just another way to send a string to console-log!")
	//js.Global().Get("document").Call("getElementsByTagName", "body").Index(0).Set("innerText", time.Now().String())

	//keepAlive()
	/*
		fmt.Println("HIER")
		fmt.Println(js.Global().Get("dataaa").Index(1))
		fmt.Println("BIER")
		fmt.Println(windowbase.Get("dataaa"))

		dataaaJS := windowbase.Get("dataaa")
		var bb []byte
		fmt.Println(dataaaJS)
		fmt.Println(bb)

		//	windowbase.Set("dataaa", js.ValueOf([]interface{}{1, 2, 3, 4, 5, 6, 7, 9}))
		fmt.Println("GIER")
	*/
	//chartarea.Set("innerHTML", "")
	chartarea.Set("innerHTML", ca0)
	scriptarea.Set("innerHTML", insebody0)

	js.Global().Set("removeAllData", js.FuncOf(removeAllDataGo))
	js.Global().Set("addAllData", js.FuncOf(addAllDataGo))
	js.Global().Set("pseudoSubmit", js.FuncOf(pseudoSubmitData.pseudoSubmit))
	//log.Println(  submitbutton      Set("onclick", "pseudoSubmit"))
	submitbutton.Call(archiumwasm.ELEMENTS_METHOD_setAttribute, "onclick", "pseudoSubmit()")

	/*TODO: WICHTIG nicht löschen
	_, _, checked_result = archiumwasm.GetCheckedRadioOrCheckbox(dombase.Call(archiumwasm.DOCUMENTS_METHOD_getElementsByName, "form_results_radio")) //Ändert sich nach neuer Arbeitsweise ja nicht mehr.
	var firstTimeEqual bool
	*/

	for ; true; time.Sleep(barseTuration(LOOPTAKT)) {
		s, l := closureGetIdWhichJustChanged(dombase, metrics.OneJumpPoints)

		//log.Println("Websocket loop started")

		//botz := dombase.Call("getElementById", "input_"+string(metrics.MT1dataverses))
		//botz := dombase.Call("getElementById", "form_types") //.Get("innerHTML")
		//dombase.Call("getElementById", "form_types")
		//botz.Call("createAttribute", "checked")
		//botz.Call("setAttribute", "checked", "true")
		//fmt.Println(botz.Call("getAttribute", "checked").String())

		//		log.Println(botz.Index(0).Get("checked"))
		//		log.Println(botz.Index(1).Get("checked"))
		//		log.Println(botz.Index(2).IsUndefined())

		//log.Println(dombase.Call(archiumwasm.DOCUMENTS_METHOD_getElementById, "input_"+string(metrics.ST1_total)).Get("value").String())

		/*FIXME: Wichtig Nicht löschen

		_, _, checked_type = archiumwasm.GetCheckedRadioOrCheckbox(dombase.Call(archiumwasm.DOCUMENTS_METHOD_getElementsByName, "form_types_radio"))
		newcheckers = archiumwasm.GetStatusFromBulkOfIds(dombase, []string{
			//"input_" + string(metrics.MT1dataverses),
			//"input_" + string(metrics.MT2datasets),
			//"input_" + string(metrics.MT3files),
			//"input_" + string(metrics.MT4downloads),
			//"input_" + string(metrics.MT5filedownloads),
			//"input_" + string(metrics.MT6uniquefiledownloads),
			//"input_" + string(metrics.RT1json),
			//"input_" + string(metrics.RT2csv),
			"input_" + string(metrics.ST1_total),
			"input_" + string(metrics.ST2_tomonth),
			"input_" + string(metrics.ST3_pastdays),
			"input_" + string(metrics.ST4_monthly),
			"input_" + string(metrics.ST5_tree),
		})
		*/

		//dombase.Call("getElementById", metrics.IDRequestCriteriaPrefix+metrics.MT1dataverses).Call("setAttribute", "checked", "true")
		//wasm.GetStatusFromBulkOfIds(dombase, metrics.FilterStacklist(metrics.OneJumpPoints, 0))

		//testarea.Set("innerHTML", fmt.Sprintf("OneJumpPointSet: %v<br><br>", "TEST"))

		//log.Println(oldcheckers)
		//log.Println(newcheckers)
		//log.Println(reflect.DeepEqual(oldcheckers, newcheckers))

		/*TODO: Wichtig nicht löschen
		if reflect.DeepEqual(oldcheckers, newcheckers) && oldchecked_type == checked_type {
			if !firstTimeEqual {
				firstTimeEqual = true

				//_, _, checked_type = archiumwasm.GetCheckedRadioOrCheckbox(dombase.Call(archiumwasm.DOCUMENTS_METHOD_getElementsByName, "form_types_radio"))
				//_, _, checked_result = archiumwasm.GetCheckedRadioOrCheckbox(dombase.Call(archiumwasm.DOCUMENTS_METHOD_getElementsByName, "form_results_radio"))

				triggerResultprintation(metrics.MetricsType(checked_type), metrics.ReturnformatType(checked_result), newcheckers, bodyInject)

			}
			//windowbase.Set("dataaa", js.ValueOf([]interface{}{9, 2, 3, 8, 5, 6, 2, 1}))
			// _ = windowbase.Get("fubagchart").Call("update", "")
		} else {
			oldcheckers = newcheckers
			oldchecked_type = checked_type
			firstTimeEqual = false
			//scriptarea.Set("innerHTML", insebody0)

			//dataaaJS := windowbase.Get("fubagchart")
			//_ = dataaaJS.Call("update", "")

			//_ =js.Global().Call("alert", 123)
			//windowbase.Set("dataaa", js.ValueOf([]interface{}{1, 2, 3, 4, 5, 6, 7, 9}))
			//_ = windowbase.Get("fubagchart").Call("update", "")
		}
		*/

		pseudoSubmitData.changeTicker(s, l)

		if !reflect.DeepEqual(oldPseudoSubmitData, pseudoSubmitData) {
			pseudoSubmitData.triggerResultprintationGedöhnz(bodyInject)
		}
		oldPseudoSubmitData = pseudoSubmitData
	}

}
