package main

import (
	"flag"
	"fmt"
	"image"
	_ "image/gif"
	_ "image/jpeg"
	_ "image/png"
	"log"
	"os"

	_ "github.com/spakin/netpbm"

	"gitea.narnian.us/lordwelch/goimagehash"
	_ "github.com/gen2brain/avif"
	_ "golang.org/x/image/bmp"
	_ "golang.org/x/image/tiff"
	_ "golang.org/x/image/webp"
)

func main() {
	imPath := flag.String("file", "", "image file to hash")
	flag.Parse()
	if imPath == nil || *imPath == "" {
		flag.Usage()
		os.Exit(1)
	}

	file, err := os.Open(*imPath)
	if err != nil {
		log.Printf("Failed to open file %s: %s", *imPath, err)
		os.Exit(1)
	}
	defer file.Close()
	im, format, err := image.Decode(file)
	if err != nil {
		msg := fmt.Sprintf("Failed to decode Image: %s", err)
		log.Println(msg)
		os.Exit(1)
	}

	if format == "webp" {
		if ycbcr, ok := im.(*image.YCbCr); ok {
			im = goimagehash.FancyUpscale(ycbcr)
		}
	}

	var (
		ahash *goimagehash.ImageHash
		dhash *goimagehash.ImageHash
		phash *goimagehash.ImageHash
	)

	ahash, err = goimagehash.AverageHash(im)
	if err != nil {
		msg := fmt.Sprintf("Failed to ahash Image: %s", err)
		log.Println(msg)
		os.Exit(1)
	}
	dhash, err = goimagehash.DifferenceHash(im)
	if err != nil {
		msg := fmt.Sprintf("Failed to dhash Image: %s", err)
		log.Println(msg)
		os.Exit(1)
	}
	phash, err = goimagehash.PerceptionHash(im)
	if err != nil {
		msg := fmt.Sprintf("Failed to phash Image: %s", err)
		log.Println(msg)
		os.Exit(1)
	}

	fmt.Printf("ahash: %s\n", ahash.BinString())
	fmt.Printf("dhash: %s\n", dhash.BinString())
	fmt.Printf("phash: %s\n", phash.BinString())
}
