package services

import (
	"context"
	"time"

	"gitea.henriburau.de/haw-lan/cod4watcher/models"
)

type CaptureService struct {
	p models.Persistence
}

func NewCaptureService(persistence models.Persistence) *CaptureService {
	return &CaptureService{
		p: persistence,
	}
}

func (cs *CaptureService) CreateCapture(ctx context.Context, capture *models.Capture) error {
	return cs.p.CreateCapture(ctx, capture)
}

func (cs *CaptureService) DeleteCapture(ctx context.Context, id int64) error {
	return cs.p.DeleteCapture(ctx, id)
}

func (cs *CaptureService) GetActiveCapures(ctx context.Context) ([]models.Capture, error) {
	captures, err := cs.p.GetCaptures(ctx)
	if err != nil {
		return nil, err
	}

	var result []models.Capture
	for _, capture := range captures {
		if capture.Active {
			result = append(result, capture)
		}
	}

	return result, nil
}

func (cs *CaptureService) GetServerStatus(ctx context.Context, capture *models.Capture) (*models.CoD4ServerStatus, error) {
	server, err := models.NewCOD4ServerStatus(capture.Host, capture.Port, time.Second)
	if err != nil {
		return nil, err
	}

	return server.GetServerStatus()
}

func (cs *CaptureService) GetCaptureById(ctx context.Context, id int64) (*models.Capture, error) {
	capture, err := cs.p.GetCapturesByID(ctx, id)
	if err != nil {
		return nil, err
	}

	return capture, nil
}
