package tui

import (
	"pingo/internal/ping"
	"time"

	"github.com/charmbracelet/lipgloss"
)

type Address struct {
	Address     string
	results     []float64
	max_results int
}

func (a *Address) Truncate() (truncated bool) {
	if len(a.results) > a.max_results {
		a.results = a.results[1:len(a.results)] // return modified slice missing first index
		return true
	}

	return false
}

// Wraps [ping.Ping]
func (a *Address) Ping() (delay float64, err error) {
	return ping.Ping(a.Address)
}

// Poll pings the affiliated Address and appends it to a.results
func (a *Address) Poll() (success bool, err error) {
	if delay, err := a.Ping(); err == nil {
		a.results = append(a.results, delay)
		a.Truncate() // enforce max length
		return true, nil
	} else {
		a.results = append(a.results, delay)
		a.Truncate() // enforce max length
		return false, err
	}
}

// Last returns the last result in [Address.results]. Returns -1 if no previous result
func (a *Address) Last() (delay float64) {
	if len(a.results) > 0 {
		return a.results[len(a.results)-1]
	} else {
		return -1
	}
}

// [tea.Msg] signatures

type tickMsg time.Time

// A simple boolean flag sent when the program is ready to poll addresses
type pollMsg bool

// / A simple error message binding to conform to type [tea.Cmd]
type errMsg struct{ err error }

func (e errMsg) Error() string { return e.err.Error() }

// Style Defintions

// A style for chart headers
var headerStyle = lipgloss.NewStyle().
	Bold(true).
	Italic(true)

// A style for info text
var infoStyle = lipgloss.NewStyle().
	Italic(true).
	Faint(true)

// A style for the base colour
// var baseColor = lipgloss.NewStyle().
// 	Foreground(lipgloss.Color("#19535f"))

// A style for the lower colour
// var lowerColor = lipgloss.NewStyle().
// 	Foreground(lipgloss.Color("#0b7a75"))

// A style for the middle colour
// var middleColor = lipgloss.NewStyle().
// 	Foreground(lipgloss.Color("#d7c9aa"))

// A style for the secondary colour
var secondaryColor = lipgloss.NewStyle().
	Foreground(lipgloss.Color("#7b2d26"))

	// A style for the primary colour
	// var primaryColor = lipgloss.NewStyle().
	// 	Foreground(lipgloss.Color("#f0f3f5"))
