package main

import (
	"Toolbox/goDataverseStrict/metrics"
	"fmt"
	"log"
	"strconv"
	"strings"
	"syscall/js"
	"time"

	"git.archium.org/archium_public/ebkTools/wasm"
)

type lokalRequestType metrics.RequestComponentsType

func metricsSelectDispatcher(server_url, api_token string, rcs metrics.RequestComponentsType) (mdat []byte, mres string) {
	var err error
	var mtypeOrMdctypeCombi string

	//var header map[string]string
	header := make(map[string]string)

	if len(api_token) > 0 {
		header["X-Dataverse-key"] = api_token
	}
	if len(rcs.Level3ReturnformatType) > 0 {
		header["Accept"] = string(rcs.Level3ReturnformatType)
	}

	switch rcs.Level0MetricsType {
	case string(metrics.MT7makeDataCount):
		mtypeOrMdctypeCombi = rcs.Level0MetricsType + "/" + rcs.Level1MetricsDataCountType
	default:
		mtypeOrMdctypeCombi = rcs.Level0MetricsType
	}

	switch rcs.Level2SearchType {
	case string(metrics.ST1total):
		mdat, mres = metrics.MetricsTotal(PDPURL, "", metrics.ReturnformatType(rcs.Level3ReturnformatType), mtypeOrMdctypeCombi)
	case string(metrics.ST2tomonth):
		ts, _ := time.Parse("2006-01", rcs.Level21UserInput)
		mdat, mres = metrics.MetricsToMonth(PDPURL, "", metrics.ReturnformatType(rcs.Level3ReturnformatType), mtypeOrMdctypeCombi, ts)
	case string(metrics.ST3pastdays):
		mdat, mres = metrics.MetricsPastDays(PDPURL, "", metrics.ReturnformatType(rcs.Level3ReturnformatType), mtypeOrMdctypeCombi, func() int {
			r, _ := strconv.Atoi(rcs.Level21UserInput)
			return r
		}())
	case string(metrics.ST4monthly):
		if len(rcs.Level21UserInput) >= 17 && strings.ContainsAny(strings.ToLower(rcs.Level21UserInput), strings.ToLower(SPANSEPARATOR)) {
			ts := func(s string) [2]time.Time {
				defer recover()
				rowvalues := make([]string, 2, 2)
				rowvalues = strings.SplitN(s, strings.ToLower(SPANSEPARATOR), 2)

				return [2]time.Time{func() (r time.Time) {
					r, _ = time.Parse("2006-01", strings.TrimSpace(rowvalues[0]))
					return
				}(), func() (r time.Time) {
					r, _ = time.Parse("2006-01", strings.TrimSpace(rowvalues[1]))
					return
				}()}
			}(strings.ToLower(rcs.Level21UserInput))

			mdat, mres = metrics.MetricsReallyMonthlySpan(PDPURL, "", metrics.ReturnformatType(rcs.Level3ReturnformatType), mtypeOrMdctypeCombi, ts)
		} else {
			mdat, mres = metrics.MetricsReallyMonthly(PDPURL, "", metrics.ReturnformatType(rcs.Level3ReturnformatType), mtypeOrMdctypeCombi)
		}
	case string(metrics.ST5tree):
		ts, _ := time.Parse("2006-01", rcs.Level21UserInput)
		mdat, mres = metrics.MetricsTree(PDPURL, "", metrics.ReturnformatType(rcs.Level3ReturnformatType), ts)
	}

	//log.Println("DEBUG:", mtypeOrMdctypeCombi)

	//res := metrics.MonthlyJsonData{}
	//json.Unmarshal([]byte(data), &res)
	//log.Println("TIE BREAK", metrics.JsonStructSelector(mdat))

	if err != nil {
		log.Fatal(err)
	}
	return
}

func (this *lokalRequestType) triggerResultprintationGedöhnz(injectpoint js.Value) {

	injectpoint.Set("innerHTML", fmt.Sprintf("%v<br>%v<br>%v %v<br>%v<br><br>", this.Level0MetricsType, this.Level1MetricsDataCountType, this.Level2SearchType, this.Level21UserInput, this.Level3ReturnformatType))

	data, request := metricsSelectDispatcher(PDPURL, "", metrics.RequestComponentsType(*this))

	//res := metrics.MonthlyJsonData{}
	//log.Println(json.Unmarshal(data, &res))
	//fmt.Println(res)

	htmlstring := fmt.Sprintf("DIE BAQUE %s<br> %s<br><br>", request, data)
	//log.Println("DIE BAQUE", htmlstring)

	//res := metrics.MonthlyJsonData{}
	//json.Unmarshal([]byte(data), &res)
	//log.Println("TIE BREAK", metrics.LinkifyDoiDoi(data))

	//https://planetary-data-portal.org/file.xhtml?persistentId=

	//var htmlstring string
	//windowbase := js.Global().Get("window")

	injectpoint.Set("innerHTML", time.Now().String()+"<br>"+htmlstring)
	//res := metrics.MonthlyJsonData{}
	/*

		json.Unmarshal(md, &res)

		label := make([]interface{}, len(res.Data), len(res.Data))
		bar0 := make([]any, len(res.Data), len(res.Data))
		bar1 := make([]any, len(res.Data), len(res.Data))
		for i := 0; i < len(res.Data); i++ {
			label[i] = res.Data[i].Date
			bar0[i] = res.Data[i].Counttotal
			bar1[i] = res.Data[i].Countmonth
		}
		//log.Println(res.Data[0].)

		_ = windowbase.Call("removeAllData", windowbase.Get("fubagchart"))
		//_ = windowbase.Call("addAllData", windowbase.Get("fubagchart"), js.ValueOf([]interface{}{[]interface{}{"Aa", "Bb"}, []interface{}{9, 2}, []interface{}{2, 9}}))

		_ = windowbase.Call("addAllData", windowbase.Get("fubagchart"), js.ValueOf([]interface{}{label, bar0, bar1}))
	*/

}

/*
func triggerResultprintation(teip metrics.MetricsType, riesaltformat metrics.ReturnformatType, deineCheckers []archiumwasm.Checkerboard, injectpoint js.Value) {

	var htmlstring string
	var windowbase js.Value

	windowbase = js.Global().Get("window")

	for _, v := range deineCheckers {
		if v.Disabled == false { //= the single one, that is enabled
			switch v.Id {
			case "input_" + string(metrics.ST1total):
				md, me := metrics.MetricsTotal(PDPURL, "", riesaltformat, teip)
				htmlstring = fmt.Sprintf("%s<br> %s<br><br>", me, md)
			case "input_" + string(metrics.ST2tomonth):
				ts, _ := time.Parse("2006-01", v.Value)
				md, me := metrics.MetricsToMonth(PDPURL, "", riesaltformat, teip, ts)
				htmlstring = fmt.Sprintf("%s<br> %s<br><br>", me, md)
			case "input_" + string(metrics.ST3pastdays):
				md, me := metrics.MetricsPastDays(PDPURL, "", riesaltformat, teip, func() int {
					r, _ := strconv.Atoi(v.Value)
					return r
				}())
				htmlstring = fmt.Sprintf("%s<br> %s<br><br>", me, md)
			case "input_" + string(metrics.ST4monthly):
				var me string
				var md []byte

				if len(v.Value) >= 17 && strings.ContainsAny(strings.ToLower(v.Value), strings.ToLower(SPANSEPARATOR)) {
					ts := func(s string) [2]time.Time {
						defer recover()
						rowvalues := make([]string, 2, 2)
						rowvalues = strings.SplitN(s, strings.ToLower(SPANSEPARATOR), 2)

						return [2]time.Time{func() (r time.Time) {
							r, _ = time.Parse("2006-01", strings.TrimSpace(rowvalues[0]))
							return
						}(), func() (r time.Time) {
							r, _ = time.Parse("2006-01", strings.TrimSpace(rowvalues[1]))
							return
						}()}
					}(strings.ToLower(v.Value))

					md, me = metrics.MetricsReallyMonthlySpan(PDPURL, "", riesaltformat, teip, ts)
				} else {
					md, me = metrics.MetricsReallyMonthly(PDPURL, "", riesaltformat, teip)
				}

				res := metrics.MonthlyJsonData{}
				json.Unmarshal(md, &res)

				label := make([]interface{}, len(res.Data), len(res.Data))
				bar0 := make([]any, len(res.Data), len(res.Data))
				bar1 := make([]any, len(res.Data), len(res.Data))
				for i := 0; i < len(res.Data); i++ {
					label[i] = res.Data[i].Date
					bar0[i] = res.Data[i].Counttotal
					bar1[i] = res.Data[i].Countmonth
				}
				//log.Println(res.Data[0].)

				_ = windowbase.Call("removeAllData", windowbase.Get("fubagchart"))
				//_ = windowbase.Call("addAllData", windowbase.Get("fubagchart"), js.ValueOf([]interface{}{[]interface{}{"Aa", "Bb"}, []interface{}{9, 2}, []interface{}{2, 9}}))

				_ = windowbase.Call("addAllData", windowbase.Get("fubagchart"), js.ValueOf([]interface{}{label, bar0, bar1}))

				htmlstring = fmt.Sprintf("%s<br> %s<br><br>", me, md)
			case "input_" + string(metrics.ST5tree):
				ts, _ := time.Parse("2006-01", v.Value)
				md, me := metrics.MetricsTree(PDPURL, "", riesaltformat, ts)
				htmlstring = fmt.Sprintf("%s<br> %s<br><br>", me, md)
			}

			//md, me := metrics.MetricsTree("https://pdp.archium.org", "", metrics.RT1json, time.Time{})
			injectpoint.Set("innerHTML", time.Now().String()+"<br>"+htmlstring)
			//log.Printf("WASM: %s<br> %s<br><br>", me, md)
		}
	}
}
*/

func actualizeForms[dings metrics.MetricsType | metrics.MetricsDataCountType | metrics.SearchType | metrics.ReturnformatType | string](injectpoint js.Value, ojpsdata []metrics.OneJumpPointSet, startlevel int8, startindex dings) {
	//disable all
	//log.Println(startlevel)
	//log.Println("HIER")
	if startlevel >= 0 {
		for i := int8(startlevel) + 1; i <= 3; i++ {
			list, _ := metrics.FilterStacklist(ojpsdata, i)
			for _, idmark := range list {
				injectpoint.Call(wasm.DOCUMENTS_METHOD_getElementById, metrics.IDRequestCriteriaPrefix+idmark).Call(wasm.ELEMENTS_METHOD_setAttribute, "disabled", "")

			}
		}

		/*
			for i := 0; i < len(ojpsdata); i++ {
				log.Println(startlevel, ojpsdata[i], startindex)
			}
		*/

		//enable any
		for i := 0; i < len(ojpsdata); i++ {
			if ojpsdata[i].Active {
				switch startlevel {
				case 0:
					injectpoint.Call(wasm.DOCUMENTS_METHOD_getElementById, metrics.IDRequestCriteriaPrefix+string(ojpsdata[i].Level0)).Call(wasm.ELEMENTS_METHOD_removeAttribute, "disabled", "")
					fallthrough
				case 1:
					if startindex == dings(ojpsdata[i].Level0) {
						injectpoint.Call(wasm.DOCUMENTS_METHOD_getElementById, metrics.IDRequestCriteriaPrefix+string(ojpsdata[i].Level1)).Call(wasm.ELEMENTS_METHOD_removeAttribute, "disabled", "")
					}
					fallthrough
				case 2:
					if startindex == dings(ojpsdata[i].Level0) || startindex == dings(ojpsdata[i].Level1) {
						injectpoint.Call(wasm.DOCUMENTS_METHOD_getElementById, metrics.IDRequestCriteriaPrefix+string(ojpsdata[i].Level2)).Call(wasm.ELEMENTS_METHOD_removeAttribute, "disabled", "")
					}
					fallthrough
				default: // ist in diesem Fall identisch mit case 3:
					if startindex == dings(ojpsdata[i].Level0) || startindex == dings(ojpsdata[i].Level1) || startindex == dings(ojpsdata[i].Level2) {
						injectpoint.Call(wasm.DOCUMENTS_METHOD_getElementById, metrics.IDRequestCriteriaPrefix+string(ojpsdata[i].Level3)).Call(wasm.ELEMENTS_METHOD_removeAttribute, "disabled", "")
					}
				}
			}
			// 	for idindex, idmark := range list {
			// 	if activity[idindex] {
			// 		injectpoint.Call(wasm.DOCUMENTS_METHOD_getElementById, metrics.IDRequestCriteriaPrefix+idmark).Call(wasm.ELEMENTS_METHOD_removeAttribute, "disabled", "")
			// 	}
			// }
		}
	}

	/*
		injectpoint.Call(wasm.DOCUMENTS_METHOD_getElementById, metrics.IDRequestCriteriaPrefix+string(metrics.MDCT2viewsTotalRegular)).Call(wasm.ELEMENTS_METHOD_setAttribute, "disabled", "")
		injectpoint.Call(wasm.DOCUMENTS_METHOD_getElementById, metrics.IDRequestCriteriaPrefix+string(metrics.MDCT2viewsTotalRegular)).Call(wasm.ELEMENTS_METHOD_removeAttribute, "disabled", "")
	*/
}
