package main

import (
	"encoding/json"
	"os"
	"sort"
	"time"
)

const CropBottom = "bottom"

type PendingImage struct {
	Date time.Time `json:"date"`
	URL  string    `json:"url"`
	Crop string    `json:"crop"`
}

type PendingImages struct {
	Images []PendingImage `json:"images"`
}

func (pi PendingImages) FindPendingImage() (bestImg PendingImage, ok bool) {
	timeNow := time.Now().UTC()

	if len(pi.Images) == 0 {
		return PendingImage{}, false
	}

	for _, img := range pi.Images {
		if timeNow.Before(img.Date) {
			continue
		}
		bestImg = img
	}
	return bestImg, bestImg.URL != ""
}

func LoadPendingImages(jsonFile string) (pi PendingImages, _ error) {
	f, err := os.Open(jsonFile)
	if err != nil {
		return PendingImages{}, err
	}
	defer f.Close()

	if err := json.NewDecoder(f).Decode(&pi); err != nil {
		return PendingImages{}, err
	}

	sort.Slice(pi.Images, func(i, j int) bool { return pi.Images[i].Date.Before(pi.Images[j].Date) })
	return pi, nil
}
