package main

import (
	"fmt"
	"image"
	"image/jpeg"
	"image/png"
	"io"
	"os"
	"path"

	"github.com/Lewuathe/gimg/ansi"
	"github.com/nfnt/resize"
)

func ViewAt(w io.Writer, p string, resolution int) {
	in, err := os.Open(p)
	if err != nil {
		panic(err)
	}
	defer in.Close()

	var src image.Image
	switch path.Ext(p) {
	case ".jpg", ".jpeg":
		src, err = jpeg.Decode(in)
	case ".png":
		src, err = png.Decode(in)
	default:
		panic(path.Ext(p))
	}
	if err != nil {
		panic(err)
	}
	printImage(w, resolution, src)
	fmt.Fprintln(w, "")
}

func printImage(w io.Writer, limit int, image image.Image) {
	if image.Bounds().Max.X > image.Bounds().Max.Y {
		xmax := image.Bounds().Max.X
		ratio := float64(limit) / float64(xmax)
		width := uint(float64(xmax) * ratio)
		image = resize.Resize(width, 0, image, resize.Bicubic)
	} else {
		ymax := image.Bounds().Max.Y
		ratio := float64(limit) / float64(ymax)
		height := uint(float64(ymax) * ratio)
		image = resize.Resize(0, height, image, resize.Bicubic)
	}
	escape := "\x1b"
	for i := 0; i < image.Bounds().Max.Y; i++ {
		for j := 0; j < image.Bounds().Max.X; j++ {
			r, g, b, _ := image.At(j, i).RGBA()
			r = ansi.To256(r)
			g = ansi.To256(g)
			b = ansi.To256(b)
			fmt.Fprintf(w, "%s[7m%s[38;2;%d;%d;%dm  ", escape, escape, r, g, b)
		}
		fmt.Fprintf(w, "\n")
	}
	fmt.Fprintf(w, "\r\n%s[0m\r", escape)
}
