package formview

import (
	"go_dreamfactory/cmd/v2/lib/common"
	"go_dreamfactory/cmd/v2/model"
	"go_dreamfactory/cmd/v2/service"
	"go_dreamfactory/cmd/v2/service/observer"
	"go_dreamfactory/comm"
	// "go_dreamfactory/modules/library"
	"go_dreamfactory/pb"

	"fyne.io/fyne/v2"
	"fyne.io/fyne/v2/widget"
	"github.com/sirupsen/logrus"
	"github.com/spf13/cast"
)

type FetterstoryView struct {
	BaseformView
	itemList *common.ItemList
	flag     bool
}

func (f *FetterstoryView) CreateView(t *model.TestCase) fyne.CanvasObject {
	jqId := widget.NewEntry()
	jqId.PlaceHolder = "羁绊ID"

	f.form.AppendItem(widget.NewFormItem("羁绊ID", jqId))

	mine := func() {
		if jqId.Text == "" {
			common.ShowTip("羁绊ID是必须的")
			return
		}
		if err := service.GetPttService().SendToClient(
			t.MainType,
			// library.LibraryFetterstoryTaskResp,
			"",
			&pb.LibraryFetterstoryTaskReq{
				FetterId: cast.ToInt32(jqId.Text),
			},
		); err != nil {
			logrus.Error(err)
			return
		}
	}

	f.form.OnSubmit = mine

	f.dataListener()
	return f.form
}

func (f *FetterstoryView) dataListener() {
	if f.flag {
		return
	}
	f.obs.AddListener(observer.EVENT_REQ_RSP, observer.Listener{
		OnNotify: func(d interface{}, args ...interface{}) {
			data := d.(*pb.UserMessage)
			if !(data.MainType == string("comm.ModuleLibrary") &&
				data.SubType == "library.LibraryActivationFetterResp") {
				return
			}
			rsp := &pb.LibraryFetterstoryTaskResp{}

			if !comm.ProtoUnmarshal(data, rsp) {
				logrus.Error("unmarshal err")
				return
			}

		},
	})
	f.flag = true
}
