/*
 * Dash API
 *
 * No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator)
 *
 * API version: 0.1
 * Generated by: OpenAPI Generator (https://openapi-generator.tech)
 */

package service

import (
	"context"
	"net/http"

	dashapi "github.com/moustachioed/dash/backend/dashapi"
	"github.com/moustachioed/dash/backend/mapping"
)

// TrackingApiService is a service that implements the logic for the TrackingApiServicer
// This service should implement the business logic for every endpoint for the TrackingApi API.
// Include any external packages or services that will be required by this service.
type TrackingApiService struct {
	ds     DataStore
	mapper mapping.Mapper
}

// NewTrackingApiService creates a default api service
func NewTrackingApiService(ds DataStore, mapper mapping.Mapper) dashapi.TrackingApiServicer {
	return &TrackingApiService{
		ds:     ds,
		mapper: mapper,
	}
}

// GetTrackingCategories -
func (s *TrackingApiService) GetTrackingCategories(ctx context.Context) (dashapi.ImplResponse, error) {
	dbcategories, err := s.ds.GetTrackingCategories()
	if err != nil {
		return dashapi.Response(http.StatusInternalServerError, nil), err
	}

	categories := s.mapper.TrackingCategoriesDbToApi(dbcategories).(dashapi.TrackingCategories)

	return dashapi.Response(http.StatusOK, categories), nil
}

// GetTrackingEntryForDate -
func (s *TrackingApiService) GetTrackingEntryForDate(ctx context.Context, date string) (dashapi.ImplResponse, error) {
	d, err := s.mapper.StringToDate(date)
	if err != nil {
		return dashapi.Response(http.StatusInternalServerError, nil), err
	}

	dbentry, err := s.ds.GetTrackingItemsForDate(d)
	if err != nil {
		return dashapi.Response(http.StatusInternalServerError, nil), err
	}

	entry := s.mapper.TrackingEntryDbToApi(dbentry).(dashapi.TrackingEntry)

	if entry.Date == "" {
		entry.Date = date
		entry.Items = []dashapi.TrackingItem{}
	}

	return dashapi.Response(http.StatusOK, entry), nil
}

// WriteTrackingEntry -
func (s *TrackingApiService) WriteTrackingEntry(ctx context.Context, trackingEntry dashapi.TrackingEntry) (dashapi.ImplResponse, error) {
	entry := s.mapper.TrackingEntryApiToDb(trackingEntry)
	err := s.ds.WriteTrackingItems(entry)
	if err != nil {
		return dashapi.Response(http.StatusInternalServerError, nil), err
	}

	return dashapi.Response(http.StatusOK, nil), nil
}
