package main

import (
	"os"
	"io/ioutil"
	"log"
	
	"github.com/faiface/pixel"
	"github.com/faiface/pixel/pixelgl"
	"github.com/faiface/pixel/text"
	"github.com/golang/freetype/truetype"
	"golang.org/x/image/font"

)

func check (err error) {
	if err != nil {
		log.Fatal(err)
	}
}

func loadTTF(path string, size float64) (font.Face, error) {
	file, err := os.Open(path)
	if err != nil {
		return nil, err
	}
	defer file.Close()

	bytes, err := ioutil.ReadAll(file)
	if err != nil {
		return nil, err
	}

	font, err := truetype.Parse(bytes)
	if err != nil {
		return nil, err
	}

	return truetype.NewFace(font, &truetype.Options{
		Size:              size,
		GlyphCacheEntries: 1,
	}), nil
}

func run() {
	cfg := pixelgl.WindowConfig{
		Title:  "Visual novel test",
		Bounds: pixel.R(0, 0, 640, 480),
		VSync:  true,
	}

	win, err := pixelgl.NewWindow(cfg)

	win.SetSmooth(true)

	face, err := loadTTF("../../Resources/mplus-1p-regular.ttf", 80)
	check(err)
	atlas := text.NewAtlas(face, text.ASCII)
	txt := text.New(pixel.V(50, 500), atlas)
	check(err)

	for !win.Closed() {
		txt.WriteString(win.Typed())
		if win.JustPressed(pixelgl.KeyEnter) {
			txt.WriteRune('\n')
		}
		txt.Draw(win, pixel.IM.Moved(win.Bounds().Center().Sub(txt.Bounds().Center())))
		win.Update()
	}
}

func main() {
	pixelgl.Run(run)
}