package grpc

import (
	"context"
	"google.golang.org/grpc"
	pb "htwkalender/common/genproto/modules"
	"htwkalender/ical/model"
	"log/slog"
	"time"
)

func GetModuleWithEvents(module model.FeedModule, conn *grpc.ClientConn) (model.Module, error) {
	c := pb.NewModuleServiceClient(conn)
	ctx, cancel := context.WithTimeout(context.Background(), time.Second)
	defer cancel()
	r, err := c.GetModule(ctx, &pb.GetModuleRequest{Uuid: module.UUID})
	if err != nil {
		slog.Error("could not get module: %v", "error", err)
	}

	events := make([]model.Event, 0)
	for _, event := range r.GetModule().Events {
		events = append(events, protoToEvent(event))
	}

	return model.Module{
		UUID:     r.GetModule().Uuid,
		Name:     r.GetModule().Name,
		Prof:     r.GetModule().Prof,
		Course:   r.GetModule().Course,
		Semester: r.GetModule().Semester,
		Events:   events,
	}, nil
}

func GetModulesWithEvents(modules []model.FeedModule, conn *grpc.ClientConn) ([]model.Module, error) {
	c := pb.NewModuleServiceClient(conn)
	ctx, cancel := context.WithTimeout(context.Background(), time.Second)
	defer cancel()

	// List of uuids
	uuids := make([]string, 0)
	for _, module := range modules {
		uuids = append(uuids, module.UUID)
	}

	r, err := c.GetModules(ctx, &pb.GetModulesRequest{Uuids: uuids})
	if err != nil {
		slog.Error("could not get modules: %v", "error", err)
	}

	moduleList := make([]model.Module, 0)
	for _, module := range r.GetModules() {
		events := make([]model.Event, 0)
		for _, event := range module.Events {
			events = append(events, protoToEvent(event))
		}

		moduleList = append(moduleList, model.Module{
			UUID:     module.Uuid,
			Name:     module.Name,
			Prof:     module.Prof,
			Course:   module.Course,
			Semester: module.Semester,
			Events:   events,
		})
	}

	return moduleList, nil
}

func protoToEvent(event *pb.Event) model.Event {

	return model.Event{
		UUID:       event.Uuid,
		Day:        event.Day,
		Week:       event.Week,
		Start:      model.ToJSONTime(event.Start),
		End:        model.ToJSONTime(event.End),
		Name:       event.Name,
		EventType:  event.EventType,
		Compulsory: event.Compulsory,
		Prof:       event.Prof,
		Rooms:      event.Rooms,
		Notes:      event.Notes,
		BookedAt:   event.BookedAt,
		Course:     event.Course,
		Semester:   event.Semester,
	}
}
