package services

import (
	"context"
	"fmt"
	"sort"

	"git.coopgo.io/coopgo-apps/parcoursmob/utils/sorting"
	fleets "git.coopgo.io/coopgo-platform/fleets/grpcapi"
	"git.coopgo.io/coopgo-platform/fleets/storage"
	"google.golang.org/grpc"
)

type FleetsService struct {
	fleets.FleetsClient
}

func NewFleetsService(dial string) (*FleetsService, error) {
	conn, err := grpc.Dial(dial, grpc.WithInsecure())

	client := fleets.NewFleetsClient(conn)
	if err != nil {
		return nil, err
	}

	return &FleetsService{
		FleetsClient: client,
	}, nil
}

func (s *ServicesHandler) GetBooking(bookingid string) (booking storage.Booking, err error) {
	request := &fleets.GetBookingRequest{
		Bookingid: bookingid,
	}
	resp, err := s.GRPC.Fleets.GetBooking(context.TODO(), request)
	if err == nil {
		booking = resp.Booking.ToStorageType()
	}
	return
}

func (s *ServicesHandler) GetBookings() (bookings []storage.Booking, err error) {
	bookings = []storage.Booking{}

	request := &fleets.GetBookingsRequest{}
	resp, err := s.GRPC.Fleets.GetBookings(context.TODO(), request)
	if err == nil {
		for _, booking := range resp.Bookings {
			bookings = append(bookings, booking.ToStorageType())
		}
		sort.Sort(sorting.BookingsByStartdate(bookings))
	}

	return
}

func (s *ServicesHandler) GetVehiclesMap() (vehicles map[string]storage.Vehicle, err error) {
	vehicles = map[string]storage.Vehicle{}

	request := &fleets.GetVehiclesRequest{
		Namespaces: []string{"parcoursmob"},
	}
	resp, err := s.GRPC.Fleets.GetVehicles(context.TODO(), request)
	if err != nil {
		fmt.Println(err)
	} else {
		for _, vehicle := range resp.Vehicles {
			vehicles[vehicle.Id] = vehicle.ToStorageType()
		}
	}

	return vehicles, err
}
