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 MailListView struct {
	BaseformView
	mailList func()
	itemList *common.ItemList
	flag     bool
}

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

	this.itemList.ItemList = this.itemList.CreateDefaultCheckList()

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

	defer this.mailList()

	refreshBtn := widget.NewButtonWithIcon("", theme.ViewRefreshIcon(), func() {
		this.itemList.Reset()
		this.mailList()
	})
	buttonBar := container.NewHBox(refreshBtn)
	c := container.NewBorder(buttonBar, nil, nil, nil, this.itemList.ItemList)

	return c
}

func (this *MailListView) 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("mail") &&
				data.SubType == "getlist") {
				return
			}
			rsp := &pb.MailGetListResp{}
			if !comm.ProtoUnmarshal(data, rsp) {
				logrus.Error("MailGetListResp unmarshal err")
				return
			}

			for i, v := range rsp.Mails {
				item := common.Item{
					Id:   v.ObjId,
					Text: fmt.Sprintf("%d-%s %s", i+1, v.Title, v.Contex),
				}
				this.itemList.AddItem(item)
			}
		},
	})
	this.flag = true
}
