package lib

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

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

func AppendToPdf(
	inputPdfFilePath string,
	inputXmlFilePath string,
	outputFilePath string,
	embedName string,
	description string,
) error {
	logger := GetDebugLogger()
	logger.Log(fmt.Sprintf("enter appendToPdf(%s, %s, %s)", inputPdfFilePath, inputXmlFilePath, outputFilePath))
	defer func() {
		logger.Log("leave appendToPdf")
	}()

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

	if inputXmlFilePath == "" {
		inputXmlFilePath = strings.TrimSuffix(inputPdfFilePath, filepath.Ext(inputPdfFilePath)) + ".xml"
	}

	if outputFilePath == "" {
		outputFilePath = strings.TrimSuffix(
			inputPdfFilePath,
			filepath.Ext(inputPdfFilePath),
		) + "_xml.pdf"
	}

	if description == "" {
		description = "Rechnung"
	}

	if embedName == "" {
		embedName = "factur-x.xml"
	}

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

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

	var doc *pdf.Document
	doc, err = pdf.OpenReaderWithOptions(inputFile, pdf.OpenOptions{
		Writable: true,
	})
	if err != nil {
		return err
	}

	var inputXmlFile *os.File
	inputXmlFile, err = os.Open(inputXmlFilePath)
	if err != nil {
		return err
	}

	var inputData []byte
	inputData, err = io.ReadAll(inputXmlFile)
	if err != nil {
		return err
	}

	err = doc.AddAttachment(attachment.Attachment{
		Name:         embedName,
		Description:  description,
		MIMEType:     "text/xml",
		Size:         int64(len(inputData)),
		Relationship: "Alternative",
		ModDate:      time.Now(),
	}, inputData)
	if err != nil {
		return err
	}

	logger.Log(doc.Writer().Version)
	err = doc.Writer().SaveAs(outputFilePath)
	if err != nil {
		return err
	}

	return nil

}
