package formview

import (
	"fmt"
	"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/pb"

	"fyne.io/fyne/v2"
	"fyne.io/fyne/v2/container"
	"fyne.io/fyne/v2/theme"
	"fyne.io/fyne/v2/widget"
	"github.com/sirupsen/logrus"
)

type HeroListView struct {
	BaseformView
	itemList common.ItemList
	flag     bool
	heroList func()
}

func (this *HeroListView) CreateView(t *model.TestCase) fyne.CanvasObject {
	this.itemList = *common.NewItemList()
	this.itemList.ItemList = this.itemList.CreateList()

	this.heroList = func() {
		if err := service.GetPttService().SendToClient(t.MainType, t.SubType, &pb.HeroListReq{}); err != nil {
			logrus.Error(err)
			return
		}
	}
	defer this.heroList()

	refreshBtn := widget.NewButtonWithIcon("", theme.ViewRefreshIcon(), func() {
		this.itemList.Reset()
		this.heroList()
	})

	//layout
	buttonBar := container.NewHBox(refreshBtn)
	c := container.NewBorder(buttonBar, nil, nil, nil, this.itemList.ItemList)

	this.DataListener()
	return c
}

func (this *HeroListView) DataListener() {
	if this.flag {
		return
	}
	this.obs.AddListener(observer.EVENT_REQ_RSP, observer.Listener{
		OnNotify: func(d interface{}, args ...interface{}) {
			data := d.(*pb.UserMessage)
			if !(data.MainType == string("comm.ModuleHero") &&
				data.SubType == "") {
				return
			}
			rsp := &pb.HeroListResp{}

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

			for i, v := range rsp.List {
				item := common.Item{
					Id: v.Id,
					Text: fmt.Sprintf("%d ID:%v Star:%d Lv:%d Type:%d Count:%d",
						i+1, v.HeroID, v.Star, v.Lv, v.CardType, v.SameCount),
				}
				this.itemList.AddItem(item)
			}

		},
	})
	this.flag = true
}
