package pdf

import (
	"context"
	"fmt"
	"time"

	"github.com/chromedp/cdproto/page"
	"github.com/chromedp/chromedp"
	"github.com/rs/zerolog/log"
	"source.gleipnir.technology/Gleipnir/nidus-sync/config"
)

func GeneratePDF(ctx context.Context, path string) ([]byte, error) {
	// create context
	chromedp.Env("CHROME_FLAGS=--no-sandbox --disable-gpu --disable-dev-shm-usage")
	chromeCtx, chromeCancel := context.WithTimeout(context.Background(), 60*time.Second)
	defer chromeCancel()
	chrome_ctx, cancel := chromedp.NewContext(chromeCtx)
	defer cancel()

	// capture pdf
	var buf []byte
	url := fmt.Sprintf("https://%s%s", config.DomainNidus, path)
	log.Info().Str("url", url).Msg("Getting with headless chrome")
	if err := chromedp.Run(chrome_ctx, printToPDF(url, &buf)); err != nil {
		return nil, fmt.Errorf("print to pdf: %w", err)
	}

	return buf, nil
}

// print a specific pdf page.
func printToPDF(urlstr string, res *[]byte) chromedp.Tasks {
	return chromedp.Tasks{
		chromedp.Navigate(urlstr),
		chromedp.ActionFunc(func(ctx context.Context) error {
			buf, _, err := page.PrintToPDF().WithPrintBackground(false).Do(ctx)
			if err != nil {
				return err
			}
			*res = buf
			return nil
		}),
	}
}
