package fonts

import (
	"log"

	_ "embed"

	"github.com/hajimehoshi/ebiten/examples/resources/fonts"
	"golang.org/x/image/font"
	"golang.org/x/image/font/opentype"
	"golang.org/x/image/font/sfnt"
)

const (
	FontDPI             = 72
	FontSizeStandard    = 16
	FontSizeLarge       = 24
	FontSizeBig         = 60
	FontSizeArcadeSmall = 8
	FontSizeArcade      = 12
	FontSizeArcadeBig   = 40
	FontSizeArcadeHuge  = 80
)

type FontStruct struct {
	Standard    font.Face
	Large       font.Face
	Glitch      font.Face
	GlitchBig   font.Face
	Arcade      font.Face
	ArcadeLarge font.Face
	ArcadeHuge  font.Face
	ArcadeSmall font.Face
}

var (

	//go:embed agencyb.ttf
	agency_ttf []byte

	//go:embed arcade_n.ttf
	arcade_ttf []byte

	SurviveFont FontStruct
)

func LoadFontFatal(src []byte) *sfnt.Font {
	tt, err := opentype.Parse(src)
	if err != nil {
		log.Fatal(err)
	}
	return tt
}

func GetFaceFatal(fnt *sfnt.Font, dpi, size float64) font.Face {
	var face font.Face
	var err error

	if dpi > 0 && size > 0 && fnt != nil {
		face, err = opentype.NewFace(fnt, &opentype.FaceOptions{
			Size:    size,
			DPI:     dpi,
			Hinting: font.HintingVertical,
		})
		if err != nil {
			log.Fatal(err)
		}
	}
	return face
}

func init() {
	SurviveFont = FontStruct{}

	fnt := LoadFontFatal(fonts.MPlus1pRegular_ttf)
	SurviveFont.Standard = GetFaceFatal(fnt, FontDPI, FontSizeStandard)
	SurviveFont.Large = GetFaceFatal(fnt, FontDPI, FontSizeLarge)

	fnt2 := LoadFontFatal(agency_ttf)
	SurviveFont.Glitch = GetFaceFatal(fnt2, FontDPI, FontSizeLarge)
	SurviveFont.GlitchBig = GetFaceFatal(fnt2, FontDPI, FontSizeBig)

	fnt3 := LoadFontFatal(arcade_ttf)
	SurviveFont.Arcade = GetFaceFatal(fnt3, FontDPI, FontSizeArcade)
	SurviveFont.ArcadeLarge = GetFaceFatal(fnt3, FontDPI, FontSizeArcadeBig)
	SurviveFont.ArcadeHuge = GetFaceFatal(fnt3, FontDPI, FontSizeArcadeHuge)
	SurviveFont.ArcadeSmall = GetFaceFatal(fnt3, FontDPI, FontSizeArcadeSmall)
}
