package mods

import (
	"fmt"
	"os"
	"strings"
	"time"

	"cdmnky.io/net/patreon-ui/local.pkg/src/config"
	"go.cdmnky.io/v2/str"
	"go.cdmnky.io/v2/utils"
)

func ProcPatreon(fn func(string), config *config.Config, playlistURL string, outfile string, maxSize int64) {

	sleepTimeout := 5

	//postProcessScript := ""
	tmpfile := Format("/tmp/%s.mp4", str.Random(12))

	interval := 0

	data, err := Dload(playlistURL)
	if err != nil {
		fmt.Println(err)
		os.Exit(1)
	}

	playlist := string(data)
	lines := strings.Split(playlist, "\n")

	now := time.Now()

	parts := []string{}
	for _, line := range lines {
		if len(line) > 0 && line[0:1] != "#" {
			parts = append(parts, line)
		}
	}

	fh, err := os.Create(tmpfile)
	if err != nil {
		fn(Format("Error: %v", err))
		time.Sleep(time.Duration(sleepTimeout) * time.Second)
	}
	defer func() {
		fmt.Printf("Closing file '%s'", tmpfile)
		fh.Close()
		if err != nil {
			fn(Format("%v", err))
			os.Exit(1)
		}
		time.Sleep(time.Duration(sleepTimeout) * time.Second)
		fmt.Println("Complete!")
	}()

	cnt := 1
	for _, part := range parts {
		fmt.Printf("Temp file............. %s\n", tmpfile)
		fmt.Printf("Outfile............... %s\n", outfile)
		fmt.Printf("Timeout............... %d\n", interval)
		fmt.Printf("# of parts to fetch... %d\n", len(parts))
		fmt.Printf("Writing to file '%s'\n", tmpfile)

		fn(Format("Fetching part %d of %d...", cnt, len(parts)))
		data, err := Dload(part)
		if err != nil && err.Error() == "errcode: 403" {
			_, err = fh.Write(data)
			if err != nil {
				fn(Format("Error: %v", err))
				time.Sleep(time.Duration(sleepTimeout) * time.Second)
			}
			break
		}

		_, err = fh.Write(data)
		if err != nil {
			fn(Format("Error: %v", err))
			time.Sleep(time.Duration(sleepTimeout) * time.Second)
		}

		if interval > 0 {
			time.Sleep(time.Duration(sleepTimeout) * time.Second)
		}
		cnt++
	}

	fileSize := GetFileSize("Temp file", tmpfile)
	if maxSize > 0 && fileSize > int64(maxSize) {
		if err = Encode(config.FFMpegBin, []string{tmpfile}); err != nil {
			fn(Format("Error: %v", err))
			time.Sleep(time.Duration(sleepTimeout) * time.Second)
		}
	} else {
		fmt.Printf("File size (%v) does not exceed max file size (%v); continuing...\n", fileSize, maxSize)
	}

	fmt.Printf("Renaming '%s' to '%s'\n", tmpfile, outfile)
	os.Rename(tmpfile, outfile)

	GetFileSize("Output file", outfile)

	//if len(postProcessScript) > 0 {
	//	execute(postProcessScript, outfile)
	//}

	elapsedTime := utils.ElapsedTime(now)
	fmt.Printf("Elapsed time: %s\n", elapsedTime)
	fmt.Printf("Download complete. Filename: '%s', Elapsed time: %s\n", outfile, elapsedTime)
	fn(Format("Complete. Elapsed time: %s\n", elapsedTime))
}