package ical

import (
	"bytes"
	"github.com/jordic/goics"
	"htwkalender/ical/model"
	"htwkalender/ical/service/connector"
	htwkalenderGrpc "htwkalender/ical/service/connector/grpc"
	"log/slog"
	"time"
)

const expirationTime = 5 * time.Minute

func Feed(app model.AppType, token string) (string, error) {
	// get feed by token
	feed, err := htwkalenderGrpc.GetFeed(token, app.GrpcClient)
	if err != nil {
		return "", err
	}

	var events model.Events

	// Get all events for modules
	events, err = htwkalenderGrpc.GetEvents(feed.Modules, app.GrpcClient)
	if err != nil {
		return "", err
	}

	// Sort events by start date
	events.Sort()

	modules := make(map[string]model.FeedCollection)
	for _, module := range feed.Modules {
		modules[module.UUID] = model.FeedCollection(module)
	}

	b := bytes.Buffer{}
	goics.NewICalEncode(&b).Encode(IcalModel{Events: events, Mapping: modules})
	icalFeed := &model.FeedModel{Content: b.String(), ExpiresAt: model.JSONTime(time.Now().Add(expirationTime))}

	return icalFeed.Content, nil
}

func FeedRecord(app model.AppType, token string) (model.FeedRecord, error) {

	feedRecord, err := connector.GetFeedByToken(app.DataManagerURL, token)
	if err != nil {
		return model.FeedRecord{}, err
	}

	return feedRecord, nil

}

func DeleteFeedRecord(app model.AppType, token string) error {
	err := connector.DeleteFeedRecord(app, token)
	if err != nil {
		return err
	}
	return nil
}

func CreateFeed(app model.AppType, modules []model.FeedCollection) (string, error) {

	// Save feed
	token, err := connector.SaveFeedRecord(app, modules)
	if err != nil {
		slog.Error("Failed to save feed", "error", err)
		return "", err
	}

	return token, nil
}
