package main

import (
	"image"
	"log"
	"os"
	"path/filepath"
	"strings"

	"github.com/disintegration/gift"

	_ "image/jpeg"
	"image/png"

	_ "golang.org/x/image/webp"
)

type ImageFilters struct {
	Colorize [3]float64
	Contrast float32
	Gamma    float32
}

func makeDefaultImageFilters() ImageFilters {
	return ImageFilters{
		Colorize: [3]float64{247, 40, 60},
		Contrast: -35,
		Gamma:    0.8,
	}
}

func hexToHSL(string) [3]int {

	return [3]int{1, 1, 1}
}

func pickRandomImage(dir string) (string, error) {

	dir = config.ImagesDir + dir
	log.Printf("getting random file from %v\n", dir)
	randomImg, filename, _ := getRandomFile(dir)
	filenameNoExt := strings.TrimSuffix(filename, filepath.Ext(filename))

	//check to see if rendered copy already exists
	fileExists, err := fileExistsInCache(filenameNoExt)
	if err != nil {
		return "", err
	}
	curr := config.Cache + filenameNoExt
	if !fileExists {
		img, err := loadImage(randomImg)
		if err != nil {
			log.Printf("failed to load image %v", randomImg)
			return "", err
		}
		dst := processImage(img, config)
		saveImage(curr, dst)
	} else {
		log.Println("file already exists in cache. skipping image processing")
	}
	return curr, nil
}

func loadImage(filename string) (image.Image, error) {
	f, err := os.Open(filename)
	if err != nil {

		return nil, err
	}
	defer f.Close()
	img, _, err := image.Decode(f)
	if err != nil {
		return nil, err
	}
	return img, nil
}

func saveImage(filename string, img image.Image) error {
	f, err := os.Create(filename)
	if err != nil {
		return err
	}
	defer f.Close()
	err = png.Encode(f, img)
	if err != nil {
		return err
	}
	return nil
}

func processImage(img image.Image, config Config) image.Image {
	h32 := float32(config.ImageFilters.Colorize[0])
	s32 := float32(config.ImageFilters.Colorize[1])
	l32 := float32(config.ImageFilters.Colorize[2])

	g := gift.New(
		gift.Colorize(h32, s32, l32),
		gift.Contrast(config.ImageFilters.Contrast),
		gift.Gamma(config.ImageFilters.Gamma),
	)

	dst := image.NewRGBA(g.Bounds(img.Bounds()))
	g.Draw(dst, img)

	return dst
}
