package clipboard

import (
	"context"

	"golang.design/x/clipboard"
)

type X11Clipboard struct{}

func NewX11() (*X11Clipboard, error) {
	if err := clipboard.Init(); err != nil {
		return nil, err
	}
	return &X11Clipboard{}, nil
}

func (c *X11Clipboard) Read() (string, error) {
	return string(clipboard.Read(clipboard.FmtText)), nil
}

func (c *X11Clipboard) Write(content string) error {
	clipboard.Write(clipboard.FmtText, []byte(content))
	return nil
}

func (c *X11Clipboard) Watch(ctx context.Context) <-chan string {
	out := make(chan string)

	go func() {
		defer close(out)

		// golang.design/x/clipboard provides a Watch function
		ch := clipboard.Watch(ctx, clipboard.FmtText)
		for {
			select {
			case <-ctx.Done():
				return
			case data, ok := <-ch:
				if !ok {
					return
				}
				if len(data) > 0 {
					out <- string(data)
				}
			}
		}
	}()

	return out
}
