package service

import (
	"context"

	"git.itzana.me/strafesnet/go-grpc/maps"
	"git.itzana.me/strafesnet/maps-service/pkg/api"
)

// ListMaps implements listMaps operation.
//
// Get list of maps.
//
// GET /maps
func (svc *Service) ListMaps(ctx context.Context, params api.ListMapsParams) ([]api.Map, error) {
	filter := maps.MapFilter{}

	if params.DisplayName.IsSet(){
		filter.DisplayName = &params.DisplayName.Value
	}
	if params.Creator.IsSet(){
		filter.Creator = &params.Creator.Value
	}
	if params.GameID.IsSet(){
		filter.GameID = &params.GameID.Value
	}

	mapList, err := svc.Maps.List(ctx, &maps.ListRequest{
		Filter: &filter,
		Page: &maps.Pagination{
			Size:   params.Limit,
			Number: params.Page,
		},
	})
	if err != nil {
		return nil, err
	}

	var resp []api.Map
	for _, item := range mapList.Maps {
		resp = append(resp, api.Map{
			ID:           item.ID,
			DisplayName:  item.DisplayName,
			Creator:      item.Creator,
			GameID:       item.GameID,
			Date:         item.Date,
		})
	}

	return resp, nil
}

// GetMap implements getScript operation.
//
// Get the specified script by ID.
//
// GET /maps/{MapID}
func (svc *Service) GetMap(ctx context.Context, params api.GetMapParams) (*api.Map, error) {
	mapResponse, err := svc.Maps.Get(ctx, &maps.IdMessage{
		ID:          params.MapID,
	})
	if err != nil {
		return nil, err
	}

	return &api.Map{
		ID:           mapResponse.ID,
		DisplayName:  mapResponse.DisplayName,
		Creator:      mapResponse.Creator,
		GameID:       mapResponse.GameID,
		Date:         mapResponse.Date,
	}, nil
}