package main

import (
	"encoding/base64"
	"github.com/playwright-community/playwright-go"
	"log"
	"os"
	"strconv"
	"time"
)

func main() {
	options := &playwright.RunOptions{
		Browsers: []string{"firefox"},
	}
	err := playwright.Install(options)
	if err != nil {
		log.Panicf("error installing playwright: %w", err)
	}

	db := openDatabase()
	defer db.Close()

	sleepTimeStr := os.Getenv("VIVAPLUS_SLEEPTIME")
	sleepTime := 15
	if sleepTimeStr != "" {
		sleepTime, err = strconv.Atoi(sleepTimeStr)
		if err != nil {
			log.Fatalf("error parsing sleep time: %v", err)
		}
	}

	w := NewWebClient(options)
	username := os.Getenv("VIVAPLUS_USER")
	password, err := base64.StdEncoding.DecodeString(os.Getenv("VIVAPLUS_PASS"))
	if err != nil {
		log.Fatalf("error decoding password: %v", err)
	}

	err = w.Login(username, string(password))
	if err != nil {
		log.Fatalf("error login in: %v", err)
	}

	for {
		err = w.DiscoverAllVideos(db)
		if err != nil {
			panic(err)
		}

		err = w.FetchVideoMetadata(db)
		if err != nil {
			panic(err)
		}

		err = DownloadAllVideos(db)
		if err != nil {
			panic(err)
		}

		log.Printf("Sleeping %d minutes until next run", sleepTime)
		time.Sleep(time.Duration(sleepTime) * time.Minute)
	}
}