package app

import (
	"io/fs"
	"os"
	"os/exec"
	"path"
	"strconv"
	"time"

	"git.sr.ht/~rockorager/vaxis"
	"git.tilde.town/nbsp/neofeels/ttbp"
	"git.tilde.town/nbsp/neofeels/ui"
	"github.com/dustin/go-humanize"
)

type Backups struct {
	title       string
	list        ui.List
	help        string
	description string
	backups     []fs.DirEntry
}

func NewBackups() *Backups {
	os.MkdirAll(ttbp.PathUserBackups, 0700)
	backups, _ := os.ReadDir(ttbp.PathUserBackups)
	list := []string{}
	for _, backup := range backups {
		timestamp, err := time.Parse("feels-backup-20060102-150405.tar.gz", backup.Name())
		if err != nil {
			continue
		}
		// XXX: for some reason this gets fucked up with timezones???
		list = append(list, humanize.Time(timestamp.Local()))
	}

	return &Backups{
		title,
		ui.NewList(list, 0),
		"↑↓/kj move  ↵ enter  q return",
		"choose a backup to restore",
		backups,
	}
}

func (backups *Backups) Event(state *ui.State, event vaxis.Event) (processed bool) {
	if key, ok := event.(vaxis.Key); ok && key.EventType == vaxis.EventPress {
		switch key.String() {
		case "Ctrl+c", "Ctrl+d":
			close(ui.Quit)
		case "Down", "j", "Ctrl+n":
			backups.list.Down()
		case "Up", "k", "Ctrl+p":
			backups.list.Up()
		case "End", "Shift+g":
			backups.list.End()
		case "Home", "g":
			backups.list.Home()
		case "0", "1", "2", "3", "4", "5", "6", "7", "8", "9":
			i, _ := strconv.Atoi(key.String())
			backups.list.SetIndex(i)
		case "q", "h", "Left":
			ui.ViewChange <- NewManagement(3)
		case "Enter", "l", "Right":
			if len(backups.list.Items()) > 0 {
				backups.LoadBackup(state)
			}
		}
		processed = true
	}
	backups.Draw(state)
	return
}

func (backups *Backups) Draw(state *ui.State) {
	exec.Command("tar", "-C", ttbp.PathUserEntries, "-xf", path.Join(ttbp.PathUserBackups, backups.backups[backups.list.Index()].Name()), "--strip-components=1", "--skip-old-files").Run()

	win := state.Window()
	win.New(win.Width/2-10, win.Height/2-8, 20, 5).Print(vaxis.Segment{Text: backups.title})
	win.New(win.Width/2-13, win.Height/2-2, 26, 1).Print(vaxis.Segment{Text: backups.description})
	backups.list.Draw(vaxis.Window{
		Vx:     win.Vx,
		Parent: nil,
		Column: win.Width/2 - 14,
		Row:    win.Height / 2,
		Width:  28,
		Height: 10,
	})
	if len(backups.list.Items()) == 0 {
		win.New(win.Width/2-8, win.Height/2+1, 16, 1).Print(vaxis.Segment{Text: "no backups found"})
	}
	win.New(win.Width/2-14, win.Height/2+11, 28, 1).Print(vaxis.Segment{Text: backups.help})
}

func (backups *Backups) LoadBackup(state *ui.State) {
	backups.Draw(state)
	win := state.Window()
	win.New(win.Width/2-14, win.Height/2+backups.list.Index(), 28, 1).Print(vaxis.Segment{
		Text: "  backup restored           ",
		Style: vaxis.Style{
			Foreground: vaxis.IndexColor(2),
			Attribute:  vaxis.AttrReverse,
		},
	})
	state.Render()
loop:
	for ev := range state.Events() {
		switch ev.(type) {
		case vaxis.Resize, vaxis.Redraw:
			backups.Draw(state)
			win.New(win.Width/2-14, win.Height/2+backups.list.Index(), 28, 1).Print(vaxis.Segment{
				Text: "  backup restored           ",
				Style: vaxis.Style{
					Foreground: vaxis.IndexColor(2),
					Attribute:  vaxis.AttrReverse,
				},
			})
			state.Render()
		case vaxis.Key:
			if ev.(vaxis.Key).EventType == vaxis.EventPress {
				break loop
			}
		}
	}
}