package controllers

import (
	"fmt"
	"log"
	"net/url"
	"os"
	"strings"

	"github.com/beego/beego/logs"
	beego "github.com/beego/beego/v2/server/web"
	"github.com/sbabiv/xml2map"
)

// WorkflowController allows to edit a tasks workflow
type WorkflowController struct {
	beego.Controller
}

// Get i
func (c *WorkflowController) Get() {

	logs.Debug("received : %v",c.Ctx.Input.RequestBody)

	c.Data["Website"] = "beego.me"
	c.Data["Email"] = "astaxie@gmail.com"
	c.TplName = "workflow.tpl"
}

// Open i
func (c *WorkflowController) Open() {

	c.Data["Website"] = "beego.me"
	c.Data["Email"] = "astaxie@gmail.com"
	c.TplName = "workflow.tpl"
}

// Save i
func (c *WorkflowController) Save() {
	xml := c.GetString("xml")
	fmt.Println(xml)
	decodedValue, err := url.QueryUnescape(xml)
	if err != nil {
		log.Fatal(err)
		return
	}
	fmt.Println(decodedValue)
	os.WriteFile("graph.xml", []byte(decodedValue), 0660)
	decoder := xml2map.NewDecoder(strings.NewReader(decodedValue))
	result, err := decoder.Decode()
	if err != nil {

	}

	cells := result["mxGraphModel"].(map[string]interface{})["root"].(map[string]interface{})["mxCell"].([]map[string]interface{})

	for _, element := range cells {
		id := element["@id"].(string)
		if _, ok := element["@style"]; ok {
			if _, ok2 := element["@rID"]; ok2 {
				fmt.Print(id + ": ")
				fmt.Println(element["@rID"], element["@rType"])
			}
		}
		if src, ok := element["@source"]; ok {
			src = element["@source"].(string)
			fmt.Println("Link: " + src.(string) + " " + element["@target"].(string))
		}
	}

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

	c.StopRun()
}

// Export i
func (c *WorkflowController) Export() {

	c.Data["Website"] = "beego.me"
	c.Data["Email"] = "astaxie@gmail.com"
	c.TplName = "workflow.tpl"
}
