// #include <u.h>
// #include <libc.h>
// #include <draw.h>
// #include <thread.h>
// #include <cursor.h>
// #include <mouse.h>
// #include <keyboard.h>
// #include <frame.h>
// #include <fcall.h>
// #include <plumb.h>
// #include <libsec.h>
// #include "dat.h"
// #include "fns.h"

package ui

import (
	"time"

	"9fans.net/go/cmd/acme/internal/adraw"
	"9fans.net/go/cmd/acme/internal/wind"
	"9fans.net/go/draw"
)

func scrsleep(dt time.Duration) {
	timer := time.NewTimer(dt)
	defer timer.Stop()
	select {
	case <-timer.C:
	case Mousectl.Mouse = <-Mousectl.C:
	}
}

func Textscroll(t *wind.Text, but int) {
	s := t.ScrollR.Inset(1)
	h := s.Max.Y - s.Min.Y
	x := (s.Min.X + s.Max.X) / 2
	oldp0 := ^0
	first := true
	for {
		adraw.Display.Flush()
		my := Mouse.Point.Y
		if my < s.Min.Y {
			my = s.Min.Y
		}
		if my >= s.Max.Y {
			my = s.Max.Y
		}
		if !(Mouse.Point == draw.Pt(x, my)) {
			adraw.Display.MoveCursor(draw.Pt(x, my))
			Mousectl.Read() // absorb event generated by moveto()
		}
		var p0 int
		if but == 2 {
			y := my
			p0 = int(int64(t.Len()) * int64(y-s.Min.Y) / int64(h))
			if p0 >= t.Q1 {
				p0 = wind.Textbacknl(t, p0, 2)
			}
			if oldp0 != p0 {
				wind.Textsetorigin(t, p0, false)
			}
			oldp0 = p0
			Mousectl.Read()
			goto Continue
		}
		if but == 1 {
			p0 = wind.Textbacknl(t, t.Org, (my-s.Min.Y)/t.Fr.Font.Height)
		} else {
			p0 = t.Org + t.Fr.CharOf(draw.Pt(s.Max.X, my))
		}
		if oldp0 != p0 {
			wind.Textsetorigin(t, p0, true)
		}
		oldp0 = p0
		// debounce
		if first {
			adraw.Display.Flush()
			time.Sleep(200 * time.Millisecond)
			select {
			default:
				// non-blocking
			case Mousectl.Mouse = <-Mousectl.C:
				// ok
			}
			first = false
		}
		scrsleep(80 * time.Millisecond)
	Continue:
		if Mouse.Buttons&(1<<(but-1)) == 0 {
			break
		}
	}
	for Mouse.Buttons != 0 {
		Mousectl.Read()
	}
}
