package ui

import (
	"go_dreamfactory/cmd/v2/lib/common"
	os_storage "go_dreamfactory/cmd/v2/lib/storage"
	"go_dreamfactory/cmd/v2/service"
	"go_dreamfactory/cmd/v2/service/observer"
	mytheme "go_dreamfactory/cmd/v2/theme"
	"io/ioutil"
	"path"
	"strings"

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

type jsonFileList struct {
	selItemId  string //选择的文件ID
	cachedList common.List
	itemList   *widget.List
	fileTotal  int //文件数

	//字段
	columnList *widget.List

}

func newJsonFileList() *jsonFileList {
	return &jsonFileList{
		cachedList: common.NewList(""),
	}
}

type appConfigValid struct {
	appAdapter
	jsonFileList *jsonFileList
	jsonDirString string //json目录
}

func (a *appConfigValid) LazyInit(pt service.PttService, obs observer.Observer) error {
	a.tabItem = container.NewTabItemWithIcon(common.TOOLBAR_VALID, mytheme.ResourceExcelJpg, nil)
	a.jsonFileList = newJsonFileList()

	//load conf
	storage, _ := os_storage.NewOSStorage()
	conf, err := storage.LoadConfig()
	if err != nil {
		logrus.Error(err)
		return err
	}

	if conf.JsonDir != "" {
		a.jsonDirString = conf.JsonDir
	}
	content := container.NewMax()
	content.Objects = []fyne.CanvasObject{}

	// 打开目录
	openFolder := func(entry *widget.Entry) {
		dConf := dialog.NewFolderOpen(func(lu fyne.ListableURI, err error) {
			if lu == nil {
				return
			}
			entry.Text = lu.Path()
			entry.Refresh()
		}, toolWin.w)
		luri, _ := fyne_storage.ListerForURI(fyne_storage.NewFileURI("."))
		dConf.SetLocation(luri)
		dConf.SetConfirmText("打开")
		dConf.SetDismissText("取消")
		dConf.Resize(fyne.NewSize(750, 500))
		dConf.Show()
	}
	//配置json路径
	jsonDir := widget.NewEntry()
	jsonDir.PlaceHolder = "json目录"
	jsonDir.OnChanged = func(s string) {
		a.jsonFileList.initItem(jsonDir.Text)
		a.jsonDirString = jsonDir.Text
	}
	form := widget.NewForm(
		widget.NewFormItem("json目录", container.NewBorder(nil, nil, nil, widget.NewButtonWithIcon("", theme.FolderIcon(), func() {
			openFolder(jsonDir)
			a.jsonFileList.initItem(jsonDir.Text)
		}), jsonDir)),
	)

	jsonDir.SetText(conf.JsonDir)

	confBtn := &widget.Button{Text: "保存配置", Icon: theme.DocumentCreateIcon()}
	confBtn.OnTapped = func() {
		conf.JsonDir = jsonDir.Text

		if err := storage.StoreConfig(conf); err != nil {
			logrus.WithField("err", err).Debug("保存配置")
			return
		}
	}

	// 创建json文件 List
	a.jsonFileList.itemList = a.jsonFileList.createList()

	//创建字段

	c := container.NewBorder(form,
		container.NewHBox(confBtn),
		nil, nil,
		container.NewGridWithColumns(3,
			container.NewVScroll(a.jsonFileList.itemList)))

	content.Objects = append(content.Objects, c)
	a.tabItem.Content = content
	return nil
}

func (a *appConfigValid) GetAppName() string {
	return common.TOOLBAR_VALID
}

func (a *appConfigValid) Icon() fyne.Resource {
	return mytheme.ResourceExcelJpg
}

func (f *jsonFileList) initItem(dir string) {
	files, err := ioutil.ReadDir(dir)
	if err != nil {
		logrus.Error(err)
		return
	}

	for _, file := range files {
		fileSuffix := path.Ext(file.Name())
		name := strings.TrimSuffix(file.Name(), fileSuffix)
		name = strings.TrimPrefix(name, "game_")
		fm := common.Item{
			Id:      file.Name(),
			Text:    name,
			Checked: false,
		}
		f.cachedList.Items = append(f.cachedList.Items, fm)
		f.fileTotal++
		// logrus.Debugf("%v", fm.Id)
	}
}

func (f *jsonFileList) createList() *widget.List {
	f.itemList = widget.NewList(
		func() int {
			return len(f.cachedList.Items)
		},
		func() fyne.CanvasObject {
			return widget.NewLabel("Template")
		},
		func(id widget.ListItemID, item fyne.CanvasObject) {
			c, _ := item.(*widget.Label)
			c.Text = f.cachedList.Items[id].Text
			c.Refresh()
		},
	)

	f.itemList.OnSelected = func(id widget.ListItemID) {
		selId := f.cachedList.Items[id].Id
		f.selItemId = selId
		return
	}
	return f.itemList
}
