package broker

import (
	"encoding/base64"
	"fmt"
	"local/truckstop/config"
	"local/truckstop/zip"
	"strings"
	"time"
)

type Job struct {
	ID      string
	URI     string
	Pickup  JobLocation
	Dropoff JobLocation
	Weight  int
	Miles   int
	Meta    string
	Pays    string
	secrets func(j *Job) `json:"-"`
}

type JobLocation struct {
	Date  time.Time
	City  string
	State string
}

func (j Job) UID() string {
	return fmt.Sprintf(
		"%v-%s-%s-%s-%s-%v",
		j.ID,
		j.Pickup.State,
		base64.StdEncoding.EncodeToString([]byte(j.Pickup.City)),
		j.Dropoff.State,
		base64.StdEncoding.EncodeToString([]byte(j.Dropoff.City)),
		j.Pickup.Date.Unix(),
	)
}

func (j *Job) Secrets() {
	if j.secrets == nil {
		return
	}
	j.secrets(j)
}

func (j Job) String() string {
	return fmt.Sprintf(
		`%s => %s (%d miles), Weight:%d, Notes:%s Link:%s`,
		j.Pickup.String(),
		j.Dropoff.String(),
		j.Miles,
		j.Weight,
		j.Meta,
		j.URI,
	)
}

func (j JobLocation) String() string {
	return fmt.Sprintf("%s, %s @ %s", j.City, j.State, j.Date.Format("Monday Jan 02"))
}

func (j Job) FormatMultilineTextDead() string {
	return fmt.Sprintf(
		"no longer available: %s,%s => %s,%s for $%v @%s",
		j.Pickup.City,
		j.Pickup.State,
		j.Dropoff.City,
		j.Dropoff.State,
		j.Pays,
		j.URI,
	)

}

func (j Job) FormatMultilineText() string {
	foo := func(client string) string {
		return fmt.Sprintf(
			"--- %s: %s => %s ---",
			client,
			j.Pickup.State,
			j.Dropoff.State,
		)
	}
	out := ""
	clients := config.Clients(j.Pickup.Date)
	useZip := config.Get().Brokers.UseZips
	zipRadius := config.Get().Brokers.RadiusMiles
	jobZip := zip.FromCityState(j.Pickup.City, j.Pickup.State)
	for k := range clients {
		should := strings.Contains(fmt.Sprint(clients[k].States), j.Pickup.State)
		if useZip {
			for _, z := range clients[k].Zips {
				should = should || zip.Get(z).MilesTo(jobZip) <= zipRadius
			}
		}
		if should {
			if len(out) > 0 {
				out += "\n"
			}
			out += foo(k)
		}
	}
	if len(out) > 0 {
		out = fmt.Sprintf(
			"%s\nPickup: %s\nDropoff: %s\nNotes: %d lbs, %d miles, %s\n%s",
			out,
			j.Pickup.String(),
			j.Dropoff.String(),
			j.Weight,
			j.Miles,
			j.Meta,
			j.URI,
		)
	}
	return out
}
