package main

import (
	"bytes"
	"encoding/json"
	"flag"
	"io"
	"log"
	"net/http"
	"os"
	"path/filepath"

	"github.com/disintegration/imaging"
)

func main() {
	headerImages := flag.String("i", "data/pending-header-images.json", "header images json file")
	targetFile := flag.String("o", "out.jpg", "target file")
	flag.Parse()

	pis, err := LoadPendingImages(*headerImages)
	if err != nil {
		log.Fatal(err)
	}

	pi, ok := pis.FindPendingImage()
	if !ok {
		log.Println("no pending image found")
		return
	}
	log.Printf("found pending image: %s\n", pi.URL)

	if err := fetchHeaderImageFromURL(*targetFile, pi); err != nil {
		log.Fatal(err)
	}

	// Write out the current pending image to the data file
	var dBfr bytes.Buffer
	if err := json.NewEncoder(&dBfr).Encode(pi); err != nil {
		log.Fatal(err)
	}
}

func fetchHeaderImageFromURL(outFile string, pi PendingImage) error {
	var bfr bytes.Buffer
	if err := fetchHeaderImage(&bfr, pi.URL); err != nil {
		log.Fatal(err)
	}

	img, err := imaging.Decode(&bfr, imaging.AutoOrientation(true))
	if err != nil {
		log.Fatal(err)
	}

	rImg := imaging.Resize(img, 1280, 0, imaging.Lanczos)

	if pi.Crop == CropBottom {
		rImg = imaging.CropAnchor(rImg, rImg.Bounds().Dx(), rImg.Bounds().Dy()/2, imaging.Bottom)
	}

	if err := os.MkdirAll(filepath.Dir(outFile), 0755); err != nil {
		log.Fatal(err)
	}

	if err := imaging.Save(rImg, outFile, imaging.JPEGQuality(70)); err != nil {
		log.Fatal(err)
	}

	return nil
}

func fetchHeaderImage(w io.Writer, url string) error {
	r, err := http.Get(url)
	if err != nil {
		return err
	}
	defer r.Body.Close()

	_, err = io.Copy(w, r.Body)
	return err
}
