package kitty

import (
	
	
	
	
	
)

// Encoder is an encoder for the Kitty graphics protocol. It supports encoding
// images in the 24-bit [RGB], 32-bit [RGBA], and [PNG] formats, and
// compressing the data using zlib.
// The default format is 32-bit [RGBA].
type Encoder struct {
	// Uses zlib compression.
	Compress bool

	// Can be one of [RGBA], [RGB], or [PNG].
	Format int
}

// Encode encodes the image data in the specified format and writes it to w.
func ( *Encoder) ( io.Writer,  image.Image) error {
	if  == nil {
		return nil
	}

	if .Compress {
		 := zlib.NewWriter()
		defer .Close() //nolint:errcheck
		 = 
	}

	if .Format == 0 {
		.Format = RGBA
	}

	switch .Format {
	case RGBA, RGB:
		 := .Bounds()
		for  := .Min.Y;  < .Max.Y; ++ {
			for  := .Min.X;  < .Max.X; ++ {
				, , ,  := .At(, ).RGBA()
				switch .Format {
				case RGBA:
					.Write([]byte{byte( >> 8), byte( >> 8), byte( >> 8), byte( >> 8)}) //nolint:errcheck,gosec
				case RGB:
					.Write([]byte{byte( >> 8), byte( >> 8), byte( >> 8)}) //nolint:errcheck,gosec
				}
			}
		}

	case PNG:
		if  := png.Encode(, );  != nil {
			return fmt.Errorf("failed to encode PNG: %w", )
		}

	default:
		return fmt.Errorf("unsupported format: %d", .Format)
	}

	return nil
}