/*
 * SPDX-FileCopyrightText: 2023 jordi fita mas <jfita@peritasoft.com>
 * SPDX-License-Identifier: AGPL-3.0-only
 */

package form

import (
	"bufio"
	"errors"
	"io"
	"mime/multipart"
	"net/http"
)

type File struct {
	Name        string
	MaxSize     int64
	Val         string
	Error       error
	ContentType string
	file        multipart.File
	header      *multipart.FileHeader
	buffer      *bufio.Reader
}

func (f *File) setError(err error) {
	f.Error = err
}

func (f *File) FillValue(r *http.Request) error {
	var err error
	f.file, f.header, err = r.FormFile(f.Name)
	if err != nil {
		if errors.Is(err, http.ErrMissingFile) {
			return nil
		}
		return err
	}
	f.buffer = bufio.NewReader(f.file)
	sniff, _ := f.buffer.Peek(512)
	f.ContentType = http.DetectContentType(sniff)
	return nil
}

func (f *File) Filename() string {
	if f.header == nil {
		return ""
	}
	return f.header.Filename
}

func (f *File) Close() error {
	if !f.HasData() {
		return nil
	}
	return f.file.Close()
}

func (f *File) HasData() bool {
	return f.file != nil
}

func (f *File) Read(p []byte) (int, error) {
	return f.buffer.Read(p)
}

func (f *File) WriteTo(w io.Writer) (int64, error) {
	return f.buffer.WriteTo(w)
}
