package main

import (
	rl "github.com/gen2brain/raylib-go/raylib"
	sg "github.com/d2fn/sumi/internal/graphics"
)

type SierpinskiArrow struct {
	dirty bool
}

func (s *SierpinskiArrow) Draw(env *Env, g *sg.Graphics) {
	rl.Translatef(env.Offscreen.Width()/2.0, env.Offscreen.Height()/2.0, 0)
	rl.ClearBackground(rl.NewColor(0, 0, 0, 0))
	sierpinskiArrow(env, int(env.Ports["sierpinskiArrowDepth"]), env.Ports["sierpinskiArrowLength"])
}

func (s *SierpinskiArrow) Update(_ *Env, g *sg.Graphics) {
	s.dirty = true
}

func (s *SierpinskiArrow) IsDirty() bool {
	return s.dirty
}

func sierpinskiArrow(env *Env, order int, length float64) {
	if order == 0 {
		curve(env, order, length, env.Ports["sierpinskiArrowAngle"])
	} else {
		rl.Rotatef(float32(env.Ports["sierpinskiArrowAngle"]), 0, 0, 1)
		curve(env, order, length, -env.Ports["sierpinskiArrowAngle"])
	}
}

func curve(env *Env, order int, length float64, angle float64) {
	if order == 0 {
		len := int32(length)
		rl.SetLineWidth(4)
		rl.DrawLine(0, 0, len, 0, rl.RayWhite)
		rl.Translatef(float32(length), 0, 0)
	} else {
		curve(env, order-1, length/2, -angle)
		rl.Rotatef(float32(angle), 0, 0, 1)
		curve(env, order-1, length/2, angle)
		rl.Rotatef(float32(angle), 0, 0, 1)
		curve(env, order-1, length/2, -angle)
	}
}
