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/modules/sociaty"
	"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 SociatyRankView struct {
	rankList func()
	BaseformView
	itemList *common.ItemList
	flag     bool
}

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

	this.itemList.ItemList = this.itemList.CreateList()
	this.rankList = func() {
		this.itemList.Reset()
		if err := service.GetPttService().SendToClient(
			string("sociaty"),
			"",
			&pb.SociatyRankReq{}); err != nil {
			logrus.Error(err)
		}
	}
	defer this.rankList()

	refreshBtn := widget.NewButtonWithIcon("", theme.ViewRefreshIcon(), func() {
		this.itemList.Reset()
		this.rankList()
	})
	buttonBar := container.NewHBox(refreshBtn)

	c := container.NewBorder(buttonBar, nil, nil, nil, this.itemList.ItemList)

	this.dataListener()
	return c
}

func (this *SociatyRankView) 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("sociaty") &&
				data.SubType == "") {
				return
			}

			rsp := &pb.SociatyRankResp{}
			if !comm.ProtoUnmarshal(data, rsp) {
				logrus.Error("unmarshal err")
				return
			}

			for i, v := range rsp.Rank {
				item := common.Item{
					Id:   v.SociatyId,
					Text: fmt.Sprintf("%d - %s 等级:%d 活跃度:%d", i+1, v.Name, v.Lv, v.Activity),
				}
				this.itemList.AddItem(item)
			}
		},
	})
	this.flag = true
}
