package ocr

import (
	// "database/sql"
	"log/slog"
	"net/http"
	"strings"

	"github.com/gin-gonic/gin"
	"github.com/otiai10/gosseract/v2"
)

type GetTextHandler struct {
	logger         slog.Logger
	// database 	   *sql.DB
	client		   gosseract.Client
}

type GetTextHandlerParams struct {
	Logger         slog.Logger
	// Database 	   *sql.DB
	Client		   gosseract.Client
}


func NewGetTextHandler(params GetTextHandlerParams) *GetTextHandler {
	return &GetTextHandler{
		logger: params.Logger,	
		// database: params.Database,
		client: params.Client,
	}
}

func (h *GetTextHandler) ServeHTTP(c *gin.Context,w http.ResponseWriter, r *http.Request) {
	file, err := c.FormFile("file")
	if err != nil {
		h.logger.Error("Error forming file", err)
	}

	fileName := "./file"

	err = c.SaveUploadedFile(file, fileName)
	if err != nil {
		h.logger.Error("Error saving file", err)
	}

	err = h.client.SetImage(fileName)
	if err != nil {
		h.logger.Error("Error setting image", err)
	}
	text, err := h.client.Text()
	if err != nil {
		h.logger.Error("Error getting text from file", err)
	}
	lines := strings.Split(text, "\n")
	c.JSON(http.StatusOK, lines)
}

