package tui

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

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
	}
}

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() }
