package nmslib

import (
	"fmt"
	"image/png"
	"io/ioutil"
	"os"
	"strconv"

	"github.com/nfnt/resize"

	gim "github.com/ozankasikci/go-image-merge"
)

/*CreateBanner - Output PNG of Portal Glyphs
Requires 3 vars and returns 0 var, Outputs a PNG file
var portalex string
	Portal Glyph hex string
var savename string
	Output name of PNG file
var vopt int
	1 enables vertical banner
	0 enables horizontal banner
*/
func CreateBanner(portalhex string, savename string, vopt int) {
	var err error
	var GlyphHex [12]int64
	var glyphImg [12]string
	var vert int
	var horz int

	// Setup temp dir
	tempdir, err := ioutil.TempDir("", "nmslib-")
	if err != nil {
		panic(err)
	}
	defer os.RemoveAll(tempdir)

	// verify len of portalhex
	if len(portalhex) == 12 {
		// get hex value from each digit in given string to an array of int64
		for i := 0; i < len(portalhex); i++ {
			GlyphHex[i], err = strconv.ParseInt(portalhex[i:int(i+1)], 16, 16)
			if err != nil {
				panic(err)
			}
		}
		// assign image location of its glyph hex value to an array of strings
		for j := 0; j < len(glyphImg); j++ {
			glyphImg[j] = fmt.Sprintf("glyphs/GLYPH-%X.png", GlyphHex[j])
		}
		// pull images need from glyph.go and saved them to ./glyphs/
		for k := 0; k < len(glyphImg); k++ {
			data, err := Asset(glyphImg[k])
			if err != nil {
				panic(err)
			}
			_, err2 := os.Stat(tempdir + "/glyphs/")
			if os.IsNotExist(err2) {
				errDir := os.MkdirAll(tempdir+"/glyphs", 0755)
				if errDir != nil {
					panic(errDir)
				}
			}

			err = ioutil.WriteFile(tempdir+"/"+glyphImg[k], []byte(data), 0644)
		}
	}
	// load images for processing using github.com/ozankasikci/go-image-merge
	grids := []*gim.Grid{
		{ImageFilePath: tempdir + "/" + glyphImg[0]}, {ImageFilePath: tempdir + "/" + glyphImg[1]},
		{ImageFilePath: tempdir + "/" + glyphImg[2]}, {ImageFilePath: tempdir + "/" + glyphImg[3]},
		{ImageFilePath: tempdir + "/" + glyphImg[4]}, {ImageFilePath: tempdir + "/" + glyphImg[5]},
		{ImageFilePath: tempdir + "/" + glyphImg[6]}, {ImageFilePath: tempdir + "/" + glyphImg[7]},
		{ImageFilePath: tempdir + "/" + glyphImg[8]}, {ImageFilePath: tempdir + "/" + glyphImg[9]},
		{ImageFilePath: tempdir + "/" + glyphImg[10]}, {ImageFilePath: tempdir + "/" + glyphImg[11]},
	}

	if vopt == 1 { // set vertical rendering
		vert, horz = 1, 12
	} else { // set horizontal rendering (default)
		vert, horz = 12, 1
	}

	// create new image from grids
	rgba, err := gim.New(grids, vert, horz).Merge()
	if err != nil {
		panic(err)
	}

	// Resize banner 768x64
	nuimg := resize.Resize(768, 64, rgba, resize.Lanczos3)

	// save the output to png
	fmt.Printf("Saving %s to %s\n", portalhex, savename)
	file, err := os.Create(savename)
	err = png.Encode(file, nuimg)
	if err != nil {
		fmt.Println(err)
	}
}
