package postman

import (
	"bytes"
	"encoding/base64"
	"os"
)

// Вложение
type Attachment struct {
	name        string
	contentType string
	withFile    bool
}

func NewAttachment(file string) Attachment {
	return Attachment{
		name:        file,
		contentType: "application/octet-stream",
		withFile:    true,
	}
}

// Импорт файла в тело письма
func (a *Attachment) WriteFile(buffer *bytes.Buffer) error {
	file, err := os.ReadFile(a.name)
	if err != nil {
		return err
	}

	//
	payload := make([]byte, base64.StdEncoding.EncodedLen(len(file)))
	base64.StdEncoding.Encode(payload, file)

	//
	buffer.WriteString("\r\n")

	for index, line := 0, len(payload); index < line; index++ {
		buffer.WriteByte(payload[index])

		if (index+1)%76 == 0 {
			_, era := buffer.WriteString("\r\n")
			if era != nil {
				return era
			}
		}
	}

	return nil
}