package tui

import (
	"errors"
	"fmt"

	//"math"
	//"strings"
	//"whspbrd/pkg/cell_size"
	"whspbrd/pkg/clean_image"
	"whspbrd/pkg/render_image"
	//"whspbrd/pkg/resize_image"

	"github.com/jroimartin/gocui"
	//"os"
)

func updateContactsView(g *gocui.Gui) error {
	v, err := g.View("users")
	if err != nil {
		return err
	}

	v.Clear()
	clear := cleanimage.NewKittyImageCleaner()
	fmt.Print(clear.DeleteByColumn(2, false))

	// TODO: If no contacts then error, create some add contacts window or hello to WhspBrd
	LoadMessages(users[selectedUserIdx])

	// TODO: Render profile image of users and change colors of each user maybe?
	if len(users) == 0 {
		fmt.Fprintln(v, "No Contacts")
		return errors.New("no contacts in the list, find some friends")
	}

	_, maxY := g.Size()
	h := min(len(users), (maxY/2)-1)
	startI := max(0, min(selectedUserIdx-(h/2), len(users)-h))

	fmt.Fprint(v, "\n\n")
	for i := startI; i < startI+h; i++ {
		u := users[i]

		fmt.Fprint(v, "\t\t\t\t")

		icon_path := fmt.Sprintf("./configs/servers/default/users/%s/icon.png", u)
		render_image.RenderImage(icon_path, 3+2*(i-startI), 2, 30, 30, false)

		if i == selectedUserIdx {
			fmt.Fprintln(v, "\x1b[7m"+u+"\x1b[0m\n")
		} else {
			fmt.Fprintln(v, u+"\n")
		}

	}
	return nil
}

// KEYBINDINGS
func nextContact(g *gocui.Gui, v *gocui.View) error {
	if len(users) == 0 {
		return nil
	}
	selectedUserIdx++
	if selectedUserIdx == len(users) {
		selectedUserIdx = 0
	}

	err := updateContactsView(g)

	updateChatView(g.Views()[1])
	return err
}

func prevContact(g *gocui.Gui, v *gocui.View) error {
	if len(users) == 0 {
		return nil
	}
	selectedUserIdx--
	if selectedUserIdx == -1 {
		selectedUserIdx = len(users) - 1
	}

	err := updateContactsView(g)

	updateChatView(g.Views()[1])
	return err
}
