package lib

import (
	"errors"
	"fmt"
	"io"
	"os"
	"path/filepath"
	"strings"

	"github.com/pdfcpu/pdfcpu/pkg/api"
	"github.com/pdfcpu/pdfcpu/pkg/pdfcpu/model"
)

func ExtractFromPdf(inputFilePath string, outputFilePath string) error {
	logger := GetDebugLogger()
	logger.Log(fmt.Sprintf("enter ExtractFromPdf(%s, %s)", inputFilePath, outputFilePath))
	defer func() {
		logger.Log("leave extractFromPdf")
	}()

	if inputFilePath == "" {
		return errors.New("no input file specified")
	}

	if outputFilePath == "" {
		outputFilePath = strings.TrimSuffix(inputFilePath, filepath.Ext(inputFilePath)) + ".xml"
	}

	logger.Log(fmt.Sprintf("pdfInput: '%s' output: '%s'", inputFilePath, outputFilePath))

	inputFile, err := os.Open(inputFilePath)
	if err != nil {
		return err
	}
	defer inputFile.Close()

	var (
		attachments []model.Attachment
		rawData     []byte
		ctx         *model.Context
		attachment  *model.Attachment
	)

	ctx, err = api.ReadContextFile(inputFilePath)
	if err != nil {
		return err
	}
	attachments, err = api.Attachments(inputFile, model.NewDefaultConfiguration())
	if err != nil {
		return err
	}

	attachment, err = ctx.ExtractAttachment(attachments[0])
	if err != nil {
		return err
	}

	rawData, err = io.ReadAll(attachment)
	if err != nil {
		return err
	}

	var outputFile *os.File
	outputFile, err = os.Create(outputFilePath)
	if err != nil {
		return err
	}
	defer outputFile.Close()

	_, err = outputFile.Write(rawData)
	if err != nil {
		return err
	}

	return nil
}
