package lib

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

	attachment2 "gitlab.com/romalor/pdflib/pkg/components/attachment"
	"gitlab.com/romalor/pdflib/pkg/pdf"
)

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 []attachment2.Attachment

	var doc *pdf.Document
	doc, err = pdf.OpenReader(inputFile)
	if err != nil {
		return err
	}

	attachments, err = doc.Attachments()
	if err != nil {
		return err
	}

	if len(attachments) == 0 {
		return errors.New("no attachments found")
	}

	err = doc.ExtractAttachment(attachments[0].Name, outputFilePath)

	return err
}
