package ui

import (
	"errors"
	"go_dreamfactory/cmd/v2/lib/common"
	"go_dreamfactory/cmd/v2/service"
	"go_dreamfactory/cmd/v2/service/observer"
	"image/color"
	"strconv"

	"fyne.io/fyne/v2"
	"fyne.io/fyne/v2/canvas"
	"fyne.io/fyne/v2/container"
	"fyne.io/fyne/v2/dialog"
	"fyne.io/fyne/v2/theme"
	"fyne.io/fyne/v2/widget"
	"github.com/sethvargo/go-password/password"
)

type appLock struct {
	appAdapter
}

func (this *appLock) LazyInit(ptService service.PttService, obs observer.Observer) error {

	this.tabItem = container.NewTabItemWithIcon(common.TOOLBAR_SEC, theme.DownloadIcon(), nil)

	content := container.NewMax()
	content.Objects = []fyne.CanvasObject{}

	title := canvas.NewText("输入密码长度", color.White)

	input := widget.NewEntry()
	input.SetPlaceHolder("长度范围10-63")

	text := canvas.NewText("", color.White)
	text.TextSize = 16

	btn := widget.NewButtonWithIcon("生成", theme.ConfirmIcon(), func() {
		passwordLength, _ := strconv.Atoi(input.Text)

		//Avoids length errors
		if passwordLength <= 10 || passwordLength >= 63 {
			passwordLength = 10
		}

		text.Text = password.MustGenerate(passwordLength, 5, 5, false, false)

		text.Refresh()
	})

	copybtn := widget.NewButtonWithIcon("复制密码", theme.ContentCopyIcon(), func() {
		if text.Text == "" {
			dialog.ShowError(errors.New("请生成密码"), toolWin.w)
			return
		}
		toolWin.w.Clipboard().SetContent(text.Text)
		common.ShowTip("已复制到剪贴板")
	})

	c := container.NewVBox(title, input, text, btn, copybtn)
	content.Objects = append(content.Objects, c)

	this.tabItem.Content = content
	return nil
}

func (a *appLock) GetAppName() string {
	return common.TOOLBAR_SEC
}
func (a *appLock) Icon() fyne.Resource {
	return theme.DownloadIcon()
}
