package main

import (
	"encoding/json"
	"fmt"
	"io"
	"log"
	"net/http"
	"os"

	"github.com/reujab/wallpaper"
)

var (
	apod APODResponse
	api_key string
)

func main() {
	if len(api_key) == 0 {
		api_key="DEMO_KEY"
	}
	resp, err := http.Get(fmt.Sprintf("https://api.nasa.gov/planetary/apod?api_key=%+v", api_key))
	if err != nil {
		log.Fatalf("\nUnable to get NASA API Response\n")
		return
	}
	decoder := json.NewDecoder(resp.Body)
	err = decoder.Decode(&apod)
	if err != nil {
		log.Fatalf("\nUnable to decode APOD Response: \n%+v\n", resp)
		return
	}
	err = wallpaper.SetFromURL(apod.Hdurl)
	if err != nil {
		log.Fatalf("\nUnable to set wallpaper: %+v\n", err)
		return
	}
	err = wallpaper.SetMode(wallpaper.Center)
	if err != nil {
		log.Fatalf("\nUnable to set wallpaper mode\n")
		return
	}
	// https://gist.github.com/mattes/d13e273314c3b3ade33f
	if _, err := os.Stat("/usr/share/backgrounds/spaceface"); !os.IsNotExist(err) {
		err = downloadFile("/usr/share/backgrounds/spaceface/lock.jpg", apod.Hdurl)
		if err != nil {
			log.Fatalf("\nUnable to Download lock.jpg image: %+v\n", err)
			return
		}
	}

}

// https://stackoverflow.com/questions/33845770/how-do-i-download-a-file-with-a-http-request-in-go-language/33845771
func downloadFile(filepath string, url string) (err error) {

	// Create the file
	out, err := os.Create(filepath)
	if err != nil {
		return err
	}
	defer out.Close()

	// Get the data
	resp, err := http.Get(url)
	if err != nil {
		return err
	}
	defer resp.Body.Close()

	// Writer the body to file
	_, err = io.Copy(out, resp.Body)
	if err != nil {
		return err
	}

	return nil
}