package services

import (
	"context"
	"pinned_message/internal/services/schedule_storage"
	"pinned_message/proto"

	"google.golang.org/grpc/codes"
	"google.golang.org/grpc/status"
)

type Services struct {
	scheduleStorage *schedule_storage.ScheduleStorage
}

func NewServices(
	scheduleStorage *schedule_storage.ScheduleStorage,
) *Services {
	return &Services{
		scheduleStorage: scheduleStorage,
	}
}

func (s *Services) GetSchedule(context.Context, *proto.GetScheduleReq) (*proto.GetScheduleRsp, error) {
	schedule, err := s.scheduleStorage.GetSchedule()
	if err != nil {
		return nil, status.Errorf(codes.Internal, err.Error())
	}

	res := &proto.GetScheduleRsp{
		UpdateTime: schedule.UpdateTime,
	}

	for _, day := range schedule.Days {
		resPerformances := make([]*proto.Performance, 0, len(day.Performances))
		for _, performance := range day.Performances {
			resNumbers := make([]*proto.Number, 0, len(performance.Numbers))
			for _, number := range performance.Numbers {
				resNumbers = append(
					resNumbers,
					&proto.Number{
						Name: number.Name,
					},
				)
			}
			resPerformances = append(
				resPerformances,
				&proto.Performance{
					TimeCollection: performance.TimeCollection,
					TimeStart:      performance.TimeStart,
					Place:          performance.Place,
					Name:           performance.Name,
					Numbers:        resNumbers,
					Costumes:       performance.Costumes,
				},
			)
		}
		res.Days = append(
			res.Days,
			&proto.Day{
				Date:         day.Date.String(),
				Performances: resPerformances,
			},
		)
	}

	return res, nil
}
